Big repository reorganization

The code is divided in three crates:
- plume-common, for the ActivityPub module, and some common utils
- plume-models, for the models and database-related code
- plume, the app itself

This new organization will allow to test it more easily, but also to create other tools that only reuse a little part of
the code (for instance a Wordpress import tool, that would just use the plume-models crate)
This commit is contained in:
Bat
2018-06-23 17:36:11 +01:00
parent 0a1edba4b0
commit 68c7aad179
40 changed files with 411 additions and 259 deletions
-137
View File
@@ -1,137 +0,0 @@
use activitypub::{Activity, Actor, Object, Link};
use array_tool::vec::Uniq;
use reqwest::Client;
use rocket::{
http::Status,
response::{Response, Responder},
request::Request
};
use serde_json;
use self::sign::Signable;
pub mod inbox;
pub mod request;
pub mod sign;
pub const CONTEXT_URL: &'static str = "https://www.w3.org/ns/activitystreams";
pub const PUBLIC_VISIBILTY: &'static str = "https://www.w3.org/ns/activitystreams#Public";
#[cfg(debug_assertions)]
pub fn ap_url(url: String) -> String {
format!("http://{}", url)
}
#[cfg(not(debug_assertions))]
pub fn ap_url(url: String) -> String {
format!("https://{}", url)
}
pub fn context() -> serde_json::Value {
json!([
CONTEXT_URL,
"https://w3id.org/security/v1",
{
"manuallyApprovesFollowers": "as:manuallyApprovesFollowers",
"sensitive": "as:sensitive",
"movedTo": "as:movedTo",
"Hashtag": "as:Hashtag",
"ostatus":"http://ostatus.org#",
"atomUri":"ostatus:atomUri",
"inReplyToAtomUri":"ostatus:inReplyToAtomUri",
"conversation":"ostatus:conversation",
"toot":"http://joinmastodon.org/ns#",
"Emoji":"toot:Emoji",
"focalPoint": {
"@container":"@list",
"@id":"toot:focalPoint"
},
"featured":"toot:featured"
}
])
}
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> {
let mut json = serde_json::to_value(&self.0).map_err(|_| Status::InternalServerError)?;
json["@context"] = context();
serde_json::to_string(&json).respond_to(request).map(|r| Response::build_from(r)
.raw_header("Content-Type", "application/activity+json")
.finalize())
}
}
pub fn broadcast<A: Activity, S: sign::Signer, T: inbox::WithInbox + Actor>(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();
let mut act = serde_json::to_value(act).unwrap();
act["@context"] = context();
let signed = act.sign(sender);
for inbox in boxes {
// TODO: run it in Sidekiq or something like that
let res = Client::new()
.post(&inbox[..])
.headers(request::headers())
.header(request::signature(sender, request::headers()))
.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(String);
impl Id {
pub fn new<T: Into<String>>(id: T) -> Id {
Id(id.into())
}
}
impl Into<String> for Id {
fn into(self) -> String {
self.0.clone()
}
}
pub trait IntoId {
fn into_id(self) -> Id;
}
impl Link for Id {}
#[derive(Clone, Debug, Default, Deserialize, Serialize, Properties)]
#[serde(rename_all = "camelCase")]
pub struct ApSignature {
#[activitystreams(concrete(PublicKey), functional)]
pub public_key: Option<serde_json::Value>
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, Properties)]
#[serde(rename_all = "camelCase")]
pub struct PublicKey {
#[activitystreams(concrete(String), functional)]
pub id: Option<serde_json::Value>,
#[activitystreams(concrete(String), functional)]
pub owner: Option<serde_json::Value>,
#[activitystreams(concrete(String), functional)]
pub public_key_pem: Option<serde_json::Value>
}
-52
View File
@@ -1,52 +0,0 @@
use base64;
use openssl::hash::{Hasher, MessageDigest};
use reqwest::{
mime::Mime,
header::{ContentType, Date, Headers, UserAgent}
};
use std::{
str::FromStr,
time::SystemTime
};
use activity_pub::sign::Signer;
const USER_AGENT: &'static str = "Plume/0.1.0";
header! {
(Signature, "Signature") => [String]
}
header! {
(Digest, "Digest") => [String]
}
pub fn headers() -> Headers {
let mut headers = Headers::new();
headers.set(UserAgent::new(USER_AGENT));
headers.set(Date(SystemTime::now().into()));
headers.set(ContentType(Mime::from_str("application/activity+json").unwrap()));
headers
}
pub fn signature<S: Signer>(signer: &S, headers: Headers) -> Signature {
let signed_string = headers.iter().map(|h| format!("{}: {}", h.name().to_lowercase(), h.value_string())).collect::<Vec<String>>().join("\n");
let signed_headers = headers.iter().map(|h| h.name().to_string()).collect::<Vec<String>>().join(" ").to_lowercase();
let data = signer.sign(signed_string);
let sign = base64::encode(&data[..]);
Signature(format!(
"keyId=\"{key_id}\",algorithm=\"rsa-sha256\",headers=\"{signed_headers}\",signature=\"{signature}\"",
key_id = signer.get_key_id(),
signed_headers = signed_headers,
signature = sign
))
}
pub fn digest(body: String) -> Digest {
let mut hasher = Hasher::new(MessageDigest::sha256()).unwrap();
hasher.update(&body.into_bytes()[..]).unwrap();
let res = base64::encode(&hasher.finish().unwrap());
Digest(format!("SHA-256={}", res))
}
-56
View File
@@ -1,56 +0,0 @@
use base64;
use chrono::Utc;
use hex;
use openssl::{
pkey::PKey,
rsa::Rsa,
sha::sha256
};
use serde_json;
/// Returns (public key, private key)
pub fn gen_keypair() -> (Vec<u8>, Vec<u8>) {
let keypair = Rsa::generate(2048).unwrap();
let keypair = PKey::from_rsa(keypair).unwrap();
(keypair.public_key_to_pem().unwrap(), keypair.private_key_to_pem_pkcs8().unwrap())
}
pub trait Signer {
fn get_key_id(&self) -> String;
/// Sign some data with the signer keypair
fn sign(&self, to_sign: String) -> Vec<u8>;
}
pub trait Signable {
fn sign<T>(&mut self, creator: &T) -> &mut Self where T: Signer;
fn hash(data: String) -> String {
let bytes = data.into_bytes();
hex::encode(sha256(&bytes[..]))
}
}
impl Signable for serde_json::Value {
fn sign<T: Signer>(&mut self, creator: &T) -> &mut serde_json::Value {
let creation_date = Utc::now().to_rfc3339();
let mut options = json!({
"type": "RsaSignature2017",
"creator": creator.get_key_id(),
"created": creation_date
});
let options_hash = Self::hash(json!({
"@context": "https://w3id.org/identity/v1",
"created": creation_date
}).to_string());
let document_hash = Self::hash(self.to_string());
let to_be_signed = options_hash + &document_hash;
let signature = base64::encode(&creator.sign(to_be_signed));
options["signaureValue"] = serde_json::Value::String(signature);
self["signature"] = options;
self
}
}
-37
View File
@@ -1,37 +0,0 @@
use diesel::{
pg::PgConnection,
r2d2::{ConnectionManager, PooledConnection}
};
use rocket::{Request, State, Outcome, http::Status, request::{self, FromRequest}};
use std::ops::Deref;
use setup::PgPool;
// From rocket documentation
// Connection request guard type: a wrapper around an r2d2 pooled connection.
pub struct DbConn(pub PooledConnection<ConnectionManager<PgConnection>>);
/// Attempts to retrieve a single connection from the managed database pool. If
/// no pool is currently managed, fails with an `InternalServerError` status. If
/// no connections are available, fails with a `ServiceUnavailable` status.
impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let pool = request.guard::<State<PgPool>>()?;
match pool.get() {
Ok(conn) => Outcome::Success(DbConn(conn)),
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ()))
}
}
}
// For the convenience of using an &DbConn as an &PgConnection.
impl Deref for DbConn {
type Target = PgConnection;
fn deref(&self) -> &Self::Target {
&self.0
}
}
+10 -48
View File
@@ -1,54 +1,19 @@
use activitypub::{
Object,
activity::{Announce, Create, Like, Undo}
};
use activitypub::activity::{Announce, Create, Like, Undo};
use diesel::PgConnection;
use failure::Error;
use serde_json;
use activity_pub::{
Id
};
use models::{
comments::*,
use plume_common::activity_pub::{Id, inbox::{Deletable, FromActivity, InboxError}};
use plume_models::{
comments::Comment,
follows::Follow,
instance::Instance,
likes,
posts::*,
reshares::*
reshares::Reshare,
posts::Post,
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 FromActivity<T: Object>: Sized {
fn from_activity(conn: &PgConnection, obj: T, actor: Id) -> Self;
fn try_from_activity(conn: &PgConnection, act: Create) -> bool {
if let Ok(obj) = act.create_props.object_object() {
Self::from_activity(conn, obj, act.create_props.actor_link::<Id>().unwrap());
true
} else {
false
}
}
}
pub trait Notify {
fn notify(&self, conn: &PgConnection);
}
pub trait Deletable {
/// true if success
fn delete_activity(conn: &PgConnection, id: Id) -> bool;
}
pub trait Inbox {
fn received(&self, conn: &PgConnection, act: serde_json::Value) -> Result<(), Error> {
let actor_id = Id::new(act["actor"].as_str().unwrap());
@@ -97,8 +62,5 @@ pub trait Inbox {
}
}
pub trait WithInbox {
fn get_inbox_url(&self) -> String;
fn get_shared_inbox_url(&self) -> Option<String>;
}
impl Inbox for Instance {}
impl Inbox for User {}
+8 -44
View File
@@ -1,64 +1,28 @@
#![feature(plugin, custom_derive, decl_macro, iterator_find_map, iterator_flatten)]
#![feature(custom_derive, decl_macro, plugin)]
#![plugin(rocket_codegen)]
extern crate activitypub;
#[macro_use]
extern crate activitystreams_derive;
extern crate activitystreams_traits;
extern crate ammonia;
extern crate array_tool;
extern crate base64;
extern crate bcrypt;
extern crate chrono;
extern crate colored;
extern crate failure;
#[macro_use]
extern crate failure_derive;
extern crate gettextrs;
extern crate heck;
extern crate hex;
#[macro_use]
extern crate hyper;
#[macro_use]
extern crate diesel;
extern crate dotenv;
#[macro_use]
extern crate lazy_static;
extern crate openssl;
extern crate pulldown_cmark;
extern crate reqwest;
extern crate failure;
extern crate gettextrs;
extern crate heck;
extern crate plume_common;
extern crate plume_models;
extern crate rocket;
extern crate rocket_contrib;
extern crate rocket_i18n;
extern crate rpassword;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate tera;
extern crate url;
extern crate webfinger;
use rocket_contrib::Template;
use std::env;
mod activity_pub;
mod db_conn;
mod models;
mod safe_string;
mod schema;
mod inbox;
mod setup;
mod routes;
mod utils;
lazy_static! {
pub static ref BASE_URL: String = env::var("BASE_URL")
.unwrap_or(format!("127.0.0.1:{}", env::var("ROCKET_PORT").unwrap_or(String::from("8000"))));
pub static ref DB_URL: String = env::var("DB_URL")
.unwrap_or(format!("postgres://plume:plume@localhost/{}", env::var("DB_NAME").unwrap_or(String::from("plume"))));
}
fn main() {
let pool = setup::check();
-24
View File
@@ -1,24 +0,0 @@
use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods, PgConnection};
use schema::blog_authors;
#[derive(Queryable, Identifiable)]
pub struct BlogAuthor {
pub id: i32,
pub blog_id: i32,
pub author_id: i32,
pub is_owner: bool,
}
#[derive(Insertable)]
#[table_name = "blog_authors"]
pub struct NewBlogAuthor {
pub blog_id: i32,
pub author_id: i32,
pub is_owner: bool,
}
impl BlogAuthor {
insert!(blog_authors, NewBlogAuthor);
get!(blog_authors);
}
-295
View File
@@ -1,295 +0,0 @@
use activitypub::{Actor, Object, CustomObject, actor::Group, collection::OrderedCollection};
use reqwest::{
Client,
header::{Accept, qitem},
mime::Mime
};
use serde_json;
use url::Url;
use chrono::NaiveDateTime;
use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods, PgConnection, dsl::any};
use openssl::{
hash::MessageDigest,
pkey::{PKey, Private},
rsa::Rsa,
sign::Signer
};
use webfinger::*;
use BASE_URL;
use activity_pub::{
ApSignature, ActivityStream, Id, IntoId, PublicKey,
inbox::WithInbox,
sign
};
use models::instance::*;
use schema::blogs;
pub type CustomGroup = CustomObject<ApSignature, Group>;
#[derive(Queryable, Identifiable, Serialize, Deserialize, Clone)]
pub struct Blog {
pub id: i32,
pub actor_id: String,
pub title: String,
pub summary: String,
pub outbox_url: String,
pub inbox_url: String,
pub instance_id: i32,
pub creation_date: NaiveDateTime,
pub ap_url: String,
pub private_key: Option<String>,
pub public_key: String
}
#[derive(Insertable)]
#[table_name = "blogs"]
pub struct NewBlog {
pub actor_id: String,
pub title: String,
pub summary: String,
pub outbox_url: String,
pub inbox_url: String,
pub instance_id: i32,
pub ap_url: String,
pub private_key: Option<String>,
pub public_key: String
}
const BLOG_PREFIX: &'static str = "~";
impl Blog {
insert!(blogs, NewBlog);
get!(blogs);
find_by!(blogs, find_by_ap_url, ap_url as String);
find_by!(blogs, find_by_name, actor_id as String, instance_id as i32);
pub fn get_instance(&self, conn: &PgConnection) -> Instance {
Instance::get(conn, self.instance_id).expect("Couldn't find instance")
}
pub fn find_for_author(conn: &PgConnection, author_id: i32) -> Vec<Blog> {
use schema::blog_authors;
let author_ids = blog_authors::table.filter(blog_authors::author_id.eq(author_id)).select(blog_authors::blog_id);
blogs::table.filter(blogs::id.eq(any(author_ids)))
.load::<Blog>(conn)
.expect("Couldn't load blogs ")
}
pub fn find_local(conn: &PgConnection, name: String) -> Option<Blog> {
Blog::find_by_name(conn, name, Instance::local_id(conn))
}
pub fn find_by_fqn(conn: &PgConnection, fqn: String) -> Option<Blog> {
if fqn.contains("@") { // remote blog
match Instance::find_by_domain(conn, String::from(fqn.split("@").last().unwrap())) {
Some(instance) => {
match Blog::find_by_name(conn, String::from(fqn.split("@").nth(0).unwrap()), instance.id) {
Some(u) => Some(u),
None => Blog::fetch_from_webfinger(conn, fqn)
}
},
None => Blog::fetch_from_webfinger(conn, fqn)
}
} else { // local blog
Blog::find_local(conn, fqn)
}
}
fn fetch_from_webfinger(conn: &PgConnection, acct: String) -> Option<Blog> {
match resolve(acct.clone()) {
Ok(wf) => wf.links.into_iter().find(|l| l.mime_type == Some(String::from("application/activity+json"))).and_then(|l| Blog::fetch_from_url(conn, l.href)),
Err(details) => {
println!("{:?}", details);
None
}
}
}
fn fetch_from_url(conn: &PgConnection, url: String) -> Option<Blog> {
let req = Client::new()
.get(&url[..])
.header(Accept(vec![qitem("application/activity+json".parse::<Mime>().unwrap())]))
.send();
match req {
Ok(mut res) => {
let text = &res.text().unwrap();
let ap_sign: ApSignature = serde_json::from_str(text).unwrap();
let mut json: CustomGroup = serde_json::from_str(text).unwrap();
json.custom_props = ap_sign; // without this workaround, publicKey is not correctly deserialized
Some(Blog::from_activity(conn, json, Url::parse(url.as_ref()).unwrap().host_str().unwrap().to_string()))
},
Err(_) => None
}
}
fn from_activity(conn: &PgConnection, acct: CustomGroup, inst: String) -> Blog {
let instance = match Instance::find_by_domain(conn, inst.clone()) {
Some(instance) => instance,
None => {
Instance::insert(conn, NewInstance {
public_domain: inst.clone(),
name: inst.clone(),
local: false
})
}
};
Blog::insert(conn, NewBlog {
actor_id: acct.object.ap_actor_props.preferred_username_string().expect("Blog::from_activity: preferredUsername error"),
title: acct.object.object_props.name_string().expect("Blog::from_activity: name error"),
outbox_url: acct.object.ap_actor_props.outbox_string().expect("Blog::from_activity: outbox error"),
inbox_url: acct.object.ap_actor_props.inbox_string().expect("Blog::from_activity: inbox error"),
summary: acct.object.object_props.summary_string().expect("Blog::from_activity: summary error"),
instance_id: instance.id,
ap_url: acct.object.object_props.id_string().expect("Blog::from_activity: id error"),
public_key: acct.custom_props.public_key_publickey().expect("Blog::from_activity: publicKey error")
.public_key_pem_string().expect("Blog::from_activity: publicKey.publicKeyPem error"),
private_key: None
})
}
pub fn into_activity(&self, _conn: &PgConnection) -> CustomGroup {
let mut blog = Group::default();
blog.ap_actor_props.set_preferred_username_string(self.actor_id.clone()).expect("Blog::into_activity: preferredUsername error");
blog.object_props.set_name_string(self.title.clone()).expect("Blog::into_activity: name error");
blog.ap_actor_props.set_outbox_string(self.outbox_url.clone()).expect("Blog::into_activity: outbox error");
blog.ap_actor_props.set_inbox_string(self.inbox_url.clone()).expect("Blog::into_activity: inbox error");
blog.object_props.set_summary_string(self.summary.clone()).expect("Blog::into_activity: summary error");
blog.object_props.set_id_string(self.ap_url.clone()).expect("Blog::into_activity: id error");
let mut public_key = PublicKey::default();
public_key.set_id_string(format!("{}#main-key", self.ap_url)).expect("Blog::into_activity: publicKey.id error");
public_key.set_owner_string(self.ap_url.clone()).expect("Blog::into_activity: publicKey.owner error");
public_key.set_public_key_pem_string(self.public_key.clone()).expect("Blog::into_activity: publicKey.publicKeyPem error");
let mut ap_signature = ApSignature::default();
ap_signature.set_public_key_publickey(public_key).expect("Blog::into_activity: publicKey error");
CustomGroup::new(blog, ap_signature)
}
pub fn update_boxes(&self, conn: &PgConnection) {
let instance = self.get_instance(conn);
if self.outbox_url.len() == 0 {
diesel::update(self)
.set(blogs::outbox_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "outbox")))
.get_result::<Blog>(conn).expect("Couldn't update outbox URL");
}
if self.inbox_url.len() == 0 {
diesel::update(self)
.set(blogs::inbox_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "inbox")))
.get_result::<Blog>(conn).expect("Couldn't update inbox URL");
}
if self.ap_url.len() == 0 {
diesel::update(self)
.set(blogs::ap_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "")))
.get_result::<Blog>(conn).expect("Couldn't update AP URL");
}
}
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<serde_json::Value> {
vec![]
}
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 webfinger(&self, conn: &PgConnection) -> Webfinger {
Webfinger {
subject: format!("acct:{}@{}", self.actor_id, self.get_instance(conn).public_domain),
aliases: vec![self.ap_url.clone()],
links: vec![
Link {
rel: String::from("http://webfinger.net/rel/profile-page"),
mime_type: None,
href: self.ap_url.clone()
},
Link {
rel: String::from("http://schemas.google.com/g/2010#updates-from"),
mime_type: Some(String::from("application/atom+xml")),
href: self.get_instance(conn).compute_box(BLOG_PREFIX, self.actor_id.clone(), "feed.atom")
},
Link {
rel: String::from("self"),
mime_type: Some(String::from("application/activity+json")),
href: self.ap_url.clone()
}
]
}
}
pub fn from_url(conn: &PgConnection, url: String) -> Option<Blog> {
Blog::find_by_ap_url(conn, url.clone()).or_else(|| {
// The requested user was not in the DB
// We try to fetch it if it is remote
if Url::parse(url.as_ref()).unwrap().host_str().unwrap() != BASE_URL.as_str() {
Blog::fetch_from_url(conn, url)
} else {
None
}
})
}
}
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 sign::Signer for Blog {
fn get_key_id(&self) -> String {
format!("{}#main-key", self.ap_url)
}
fn sign(&self, to_sign: String) -> Vec<u8> {
let key = self.get_keypair();
let mut signer = Signer::new(MessageDigest::sha256(), &key).unwrap();
signer.update(to_sign.as_bytes()).unwrap();
signer.sign_to_vec().unwrap()
}
}
impl NewBlog {
pub fn new_local(
actor_id: String,
title: String,
summary: String,
instance_id: i32
) -> NewBlog {
let (pub_key, priv_key) = sign::gen_keypair();
NewBlog {
actor_id: actor_id,
title: title,
summary: summary,
outbox_url: String::from(""),
inbox_url: String::from(""),
instance_id: instance_id,
ap_url: String::from(""),
public_key: String::from_utf8(pub_key).unwrap(),
private_key: Some(String::from_utf8(priv_key).unwrap())
}
}
}
-202
View File
@@ -1,202 +0,0 @@
use activitypub::{
activity::Create,
link,
object::{Note}
};
use chrono;
use diesel::{self, PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods, dsl::any};
use serde_json;
use activity_pub::{
ap_url, Id, IntoId, PUBLIC_VISIBILTY,
inbox::{FromActivity, Notify}
};
use models::{
get_next_id,
instance::Instance,
mentions::Mention,
notifications::*,
posts::Post,
users::User
};
use schema::comments;
use safe_string::SafeString;
use utils;
#[derive(Queryable, Identifiable, Serialize, Clone)]
pub struct Comment {
pub id: i32,
pub content: SafeString,
pub in_response_to_id: Option<i32>,
pub post_id: i32,
pub author_id: i32,
pub creation_date: chrono::NaiveDateTime,
pub ap_url: Option<String>,
pub sensitive: bool,
pub spoiler_text: String
}
#[derive(Insertable, Default)]
#[table_name = "comments"]
pub struct NewComment {
pub content: SafeString,
pub in_response_to_id: Option<i32>,
pub post_id: i32,
pub author_id: i32,
pub ap_url: Option<String>,
pub sensitive: bool,
pub spoiler_text: String
}
impl Comment {
insert!(comments, NewComment);
get!(comments);
list_by!(comments, list_by_post, post_id as i32);
find_by!(comments, find_by_ap_url, ap_url as String);
pub fn get_author(&self, conn: &PgConnection) -> User {
User::get(conn, self.author_id).unwrap()
}
pub fn get_post(&self, conn: &PgConnection) -> Post {
Post::get(conn, self.post_id).unwrap()
}
pub fn count_local(conn: &PgConnection) -> usize {
use schema::users;
let local_authors = users::table.filter(users::instance_id.eq(Instance::local_id(conn))).select(users::id);
comments::table.filter(comments::author_id.eq(any(local_authors)))
.load::<Comment>(conn)
.expect("Couldn't load local comments")
.len()
}
pub fn to_json(&self, conn: &PgConnection) -> serde_json::Value {
let mut json = serde_json::to_value(self).unwrap();
json["author"] = self.get_author(conn).to_json(conn);
let mentions = Mention::list_for_comment(conn, self.id).into_iter()
.map(|m| m.get_mentioned(conn).map(|u| u.get_fqn(conn)).unwrap_or(String::new()))
.collect::<Vec<String>>();
println!("{:?}", mentions);
json["mentions"] = serde_json::to_value(mentions).unwrap();
json
}
pub fn compute_id(&self, conn: &PgConnection) -> String {
ap_url(format!("{}#comment-{}", self.get_post(conn).ap_url, self.id))
}
}
impl FromActivity<Note> for Comment {
fn from_activity(conn: &PgConnection, note: Note, actor: Id) -> Comment {
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());
let comm = Comment::insert(conn, NewComment {
content: SafeString::new(&note.object_props.content_string().unwrap()),
spoiler_text: note.object_props.summary_string().unwrap_or(String::from("")),
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.clone().into()).unwrap().id,
sensitive: false // "sensitive" is not a standard property, we need to think about how to support it with the activitypub crate
});
// save mentions
if let Some(serde_json::Value::Array(tags)) = note.object_props.tag.clone() {
for tag in tags.into_iter() {
serde_json::from_value::<link::Mention>(tag)
.map(|m| Mention::from_activity(conn, m, comm.id, false))
.ok();
}
}
comm.notify(conn);
comm
}
}
impl Notify for Comment {
fn notify(&self, conn: &PgConnection) {
for author in self.get_post(conn).get_authors(conn) {
Notification::insert(conn, NewNotification {
title: "{{ data }} commented your article".to_string(),
data: Some(self.get_author(conn).display_name.clone()),
content: Some(self.get_post(conn).title),
link: self.ap_url.clone(),
user_id: author.id
});
}
}
}
impl NewComment {
pub fn build() -> Self {
NewComment::default()
}
pub fn content<T: AsRef<str>>(mut self, val: T) -> Self {
self.content = SafeString::new(val.as_ref());
self
}
pub fn in_response_to_id(mut self, val: Option<i32>) -> Self {
self.in_response_to_id = val;
self
}
pub fn post(mut self, post: Post) -> Self {
self.post_id = post.id;
self
}
pub fn author(mut self, author: User) -> Self {
self.author_id = author.id;
self
}
pub fn create(mut self, conn: &PgConnection) -> (Create, i32) {
let post = Post::get(conn, self.post_id).unwrap();
// We have to manually compute it since the new comment haven't been inserted yet, and it needs the activity we are building to be created
let next_id = get_next_id(conn, "comments_id_seq");
self.ap_url = Some(format!("{}#comment-{}", post.ap_url, next_id));
self.sensitive = false;
self.spoiler_text = String::new();
let (html, mentions) = utils::md_to_html(self.content.get().as_ref());
let author = User::get(conn, self.author_id).unwrap();
let mut note = Note::default();
let mut to = author.get_followers(conn).into_iter().map(User::into_id).collect::<Vec<Id>>();
to.append(&mut post
.get_authors(conn)
.into_iter()
.flat_map(|a| a.get_followers(conn))
.map(User::into_id)
.collect::<Vec<Id>>());
to.push(Id::new(PUBLIC_VISIBILTY.to_string()));
note.object_props.set_id_string(self.ap_url.clone().unwrap_or(String::new())).expect("NewComment::create: note.id error");
note.object_props.set_summary_string(self.spoiler_text.clone()).expect("NewComment::create: note.summary error");
note.object_props.set_content_string(html).expect("NewComment::create: note.content error");
note.object_props.set_in_reply_to_link(Id::new(self.in_response_to_id.map_or_else(|| Post::get(conn, self.post_id).unwrap().ap_url, |id| {
let comm = Comment::get(conn, id).unwrap();
comm.ap_url.clone().unwrap_or(comm.compute_id(conn))
}))).expect("NewComment::create: note.in_reply_to error");
note.object_props.set_published_string(chrono::Utc::now().to_rfc3339()).expect("NewComment::create: note.published error");
note.object_props.set_attributed_to_link(author.clone().into_id()).expect("NewComment::create: note.attributed_to error");
note.object_props.set_to_link_vec(to.clone()).expect("NewComment::create: note.to error");
note.object_props.set_tag_link_vec(mentions.into_iter().map(|m| Mention::build_activity(conn, m)).collect::<Vec<link::Mention>>())
.expect("NewComment::create: note.tag error");
let mut act = Create::default();
act.create_props.set_actor_link(author.into_id()).expect("NewComment::create: actor error");
act.create_props.set_object_object(note).expect("NewComment::create: object error");
act.object_props.set_id_string(format!("{}/activity", self.ap_url.clone().unwrap())).expect("NewComment::create: id error");
act.object_props.set_to_link_vec(to).expect("NewComment::create: to error");
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("NewComment::create: cc error");
(act, next_id)
}
}
-82
View File
@@ -1,82 +0,0 @@
use activitypub::{Actor, activity::{Accept, Follow as FollowAct}};
use diesel::{self, PgConnection, ExpressionMethods, QueryDsl, RunQueryDsl};
use activity_pub::{broadcast, Id, IntoId, inbox::{FromActivity, Notify, WithInbox}, sign::Signer};
use models::{
blogs::Blog,
notifications::*,
users::User
};
use schema::follows;
#[derive(Queryable, Identifiable, Associations)]
#[belongs_to(User, foreign_key = "following_id")]
pub struct Follow {
pub id: i32,
pub follower_id: i32,
pub following_id: i32
}
#[derive(Insertable)]
#[table_name = "follows"]
pub struct NewFollow {
pub follower_id: i32,
pub following_id: i32
}
impl Follow {
insert!(follows, NewFollow);
get!(follows);
/// from -> The one sending the follow request
/// target -> The target of the request, responding with Accept
pub fn accept_follow<A: Signer + IntoId + Clone, B: Clone + WithInbox + Actor + IntoId>(
conn: &PgConnection,
from: &B,
target: &A,
follow: FollowAct,
from_id: i32,
target_id: i32
) -> Follow {
let res = Follow::insert(conn, NewFollow {
follower_id: from_id,
following_id: target_id
});
let mut accept = Accept::default();
let accept_id = format!("{}#accept", follow.object_props.id_string().unwrap_or(String::new()));
accept.object_props.set_id_string(accept_id).expect("accept_follow: id error");
accept.object_props.set_to_link(from.clone().into_id()).expect("accept_follow: to error");
accept.object_props.set_cc_link_vec::<Id>(vec![]).expect("accept_follow: cc error");
accept.accept_props.set_actor_link::<Id>(target.clone().into_id()).unwrap();
accept.accept_props.set_object_object(follow).unwrap();
broadcast(&*target, accept, vec![from.clone()]);
res
}
}
impl FromActivity<FollowAct> for Follow {
fn from_activity(conn: &PgConnection, follow: FollowAct, _actor: Id) -> Follow {
let from = User::from_url(conn, follow.follow_props.actor.as_str().unwrap().to_string()).unwrap();
match User::from_url(conn, follow.follow_props.object.as_str().unwrap().to_string()) {
Some(user) => Follow::accept_follow(conn, &from, &user, follow, from.id, user.id),
None => {
let blog = Blog::from_url(conn, follow.follow_props.object.as_str().unwrap().to_string()).unwrap();
Follow::accept_follow(conn, &from, &blog, follow, from.id, blog.id)
}
}
}
}
impl Notify for Follow {
fn notify(&self, conn: &PgConnection) {
let follower = User::get(conn, self.follower_id).unwrap();
Notification::insert(conn, NewNotification {
title: "{{ data }} started following you".to_string(),
data: Some(follower.display_name.clone()),
content: None,
link: Some(follower.ap_url),
user_id: self.following_id
});
}
}
-73
View File
@@ -1,73 +0,0 @@
use chrono::NaiveDateTime;
use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods, PgConnection};
use std::iter::Iterator;
use activity_pub::{ap_url, inbox::Inbox};
use models::users::User;
use schema::{instances, users};
#[derive(Identifiable, Queryable, Serialize)]
pub struct Instance {
pub id: i32,
pub public_domain: String,
pub name: String,
pub local: bool,
pub blocked: bool,
pub creation_date: NaiveDateTime
}
#[derive(Insertable)]
#[table_name = "instances"]
pub struct NewInstance {
pub public_domain: String,
pub name: String,
pub local: bool
}
impl Instance {
pub fn get_local(conn: &PgConnection) -> Option<Instance> {
instances::table.filter(instances::local.eq(true))
.limit(1)
.load::<Instance>(conn)
.expect("Error loading local instance infos")
.into_iter().nth(0)
}
pub fn get_remotes(conn: &PgConnection) -> Vec<Instance> {
instances::table.filter(instances::local.eq(false))
.load::<Instance>(conn)
.expect("Error loading remote instances infos")
}
pub fn local_id(conn: &PgConnection) -> i32 {
Instance::get_local(conn).unwrap().id
}
insert!(instances, NewInstance);
get!(instances);
find_by!(instances, find_by_domain, public_domain as String);
pub fn block(&self) {
unimplemented!()
}
pub fn has_admin(&self, conn: &PgConnection) -> bool {
users::table.filter(users::instance_id.eq(self.id))
.filter(users::is_admin.eq(true))
.load::<User>(conn)
.expect("Couldn't load admins")
.len() > 0
}
pub fn compute_box(&self, prefix: &'static str, name: String, box_name: &'static str) -> String {
ap_url(format!(
"{instance}/{prefix}/{name}/{box_name}",
instance = self.public_domain,
prefix = prefix,
name = name,
box_name = box_name
))
}
}
impl Inbox for Instance {}
-118
View File
@@ -1,118 +0,0 @@
use activitypub::activity;
use chrono;
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
use activity_pub::{
PUBLIC_VISIBILTY,
Id,
IntoId,
inbox::{FromActivity, Deletable, Notify}
};
use models::{
notifications::*,
posts::Post,
users::User
};
use schema::likes;
#[derive(Queryable, Identifiable)]
pub struct Like {
pub id: i32,
pub user_id: i32,
pub post_id: i32,
pub creation_date: chrono::NaiveDateTime,
pub ap_url: String
}
#[derive(Default, Insertable)]
#[table_name = "likes"]
pub struct NewLike {
pub user_id: i32,
pub post_id: i32,
pub ap_url: String
}
impl Like {
insert!(likes, NewLike);
get!(likes);
find_by!(likes, find_by_ap_url, ap_url as String);
find_by!(likes, find_by_user_on_post, user_id as i32, post_id as i32);
pub fn update_ap_url(&self, conn: &PgConnection) {
if self.ap_url.len() == 0 {
diesel::update(self)
.set(likes::ap_url.eq(format!(
"{}/like/{}",
User::get(conn, self.user_id).unwrap().ap_url,
Post::get(conn, self.post_id).unwrap().ap_url
)))
.get_result::<Like>(conn).expect("Couldn't update AP URL");
}
}
pub fn delete(&self, conn: &PgConnection) -> activity::Undo {
diesel::delete(self).execute(conn).unwrap();
let mut act = activity::Undo::default();
act.undo_props.set_actor_link(User::get(conn, self.user_id).unwrap().into_id()).expect("Like::delete: actor error");
act.undo_props.set_object_object(self.into_activity(conn)).expect("Like::delete: object error");
act.object_props.set_id_string(format!("{}#delete", self.ap_url)).expect("Like::delete: id error");
act.object_props.set_to_link(Id::new(PUBLIC_VISIBILTY.to_string())).expect("Like::delete: to error");
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Like::delete: cc error");
act
}
pub fn into_activity(&self, conn: &PgConnection) -> activity::Like {
let mut act = activity::Like::default();
act.like_props.set_actor_link(User::get(conn, self.user_id).unwrap().into_id()).expect("Like::into_activity: actor error");
act.like_props.set_object_link(Post::get(conn, self.post_id).unwrap().into_id()).expect("Like::into_activity: object error");
act.object_props.set_to_link(Id::new(PUBLIC_VISIBILTY.to_string())).expect("Like::into_activity: to error");
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Like::into_activity: cc error");
act.object_props.set_id_string(self.ap_url.clone()).expect("Like::into_activity: id error");
act
}
}
impl FromActivity<activity::Like> for Like {
fn from_activity(conn: &PgConnection, like: activity::Like, _actor: Id) -> Like {
let liker = User::from_url(conn, like.like_props.actor.as_str().unwrap().to_string());
let post = Post::find_by_ap_url(conn, like.like_props.object.as_str().unwrap().to_string());
let res = Like::insert(conn, NewLike {
post_id: post.unwrap().id,
user_id: liker.unwrap().id,
ap_url: like.object_props.id_string().unwrap_or(String::from(""))
});
res.notify(conn);
res
}
}
impl Notify for Like {
fn notify(&self, conn: &PgConnection) {
let liker = User::get(conn, self.user_id).unwrap();
let post = Post::get(conn, self.post_id).unwrap();
for author in post.get_authors(conn) {
let post = post.clone();
Notification::insert(conn, NewNotification {
title: "{{ data }} liked your article".to_string(),
data: Some(liker.display_name.clone()),
content: Some(post.title),
link: Some(post.ap_url),
user_id: author.id
});
}
}
}
impl Deletable for Like {
fn delete_activity(conn: &PgConnection, id: Id) -> bool {
if let Some(like) = Like::find_by_ap_url(conn, id.into()) {
like.delete(conn);
true
} else {
false
}
}
}
-113
View File
@@ -1,113 +0,0 @@
use activitypub::link;
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
use activity_pub::inbox::Notify;
use models::{
comments::Comment,
notifications::*,
posts::Post,
users::User
};
use schema::mentions;
#[derive(Queryable, Identifiable, Serialize, Deserialize)]
pub struct Mention {
pub id: i32,
pub mentioned_id: i32,
pub post_id: Option<i32>,
pub comment_id: Option<i32>,
pub ap_url: String // TODO: remove, since mentions don't have an AP URL actually, this field was added by mistake
}
#[derive(Insertable)]
#[table_name = "mentions"]
pub struct NewMention {
pub mentioned_id: i32,
pub post_id: Option<i32>,
pub comment_id: Option<i32>,
pub ap_url: String
}
impl Mention {
insert!(mentions, NewMention);
get!(mentions);
find_by!(mentions, find_by_ap_url, ap_url as String);
list_by!(mentions, list_for_user, mentioned_id as i32);
list_by!(mentions, list_for_post, post_id as i32);
list_by!(mentions, list_for_comment, comment_id as i32);
pub fn get_mentioned(&self, conn: &PgConnection) -> Option<User> {
User::get(conn, self.mentioned_id)
}
pub fn get_post(&self, conn: &PgConnection) -> Option<Post> {
self.post_id.and_then(|id| Post::get(conn, id))
}
pub fn get_comment(&self, conn: &PgConnection) -> Option<Comment> {
self.comment_id.and_then(|id| Comment::get(conn, id))
}
pub fn build_activity(conn: &PgConnection, ment: String) -> link::Mention {
let user = User::find_by_fqn(conn, ment.clone());
let mut mention = link::Mention::default();
mention.link_props.set_href_string(user.clone().map(|u| u.ap_url).unwrap_or(String::new())).expect("Error setting mention's href");
mention.link_props.set_name_string(format!("@{}", ment)).expect("Error setting mention's name");
mention
}
pub fn to_activity(&self, conn: &PgConnection) -> link::Mention {
let user = self.get_mentioned(conn);
let mut mention = link::Mention::default();
mention.link_props.set_href_string(user.clone().map(|u| u.ap_url).unwrap_or(String::new())).expect("Error setting mention's href");
mention.link_props.set_name_string(user.map(|u| format!("@{}", u.get_fqn(conn))).unwrap_or(String::new())).expect("Error setting mention's name");
mention
}
pub fn from_activity(conn: &PgConnection, ment: link::Mention, inside: i32, in_post: bool) -> Option<Self> {
let ap_url = ment.link_props.href_string().unwrap();
let mentioned = User::find_by_ap_url(conn, ap_url).unwrap();
if in_post {
Post::get(conn, inside.clone().into()).map(|post| {
let res = Mention::insert(conn, NewMention {
mentioned_id: mentioned.id,
post_id: Some(post.id),
comment_id: None,
ap_url: ment.link_props.href_string().unwrap_or(String::new())
});
res.notify(conn);
res
})
} else {
Comment::get(conn, inside.into()).map(|comment| {
let res = Mention::insert(conn, NewMention {
mentioned_id: mentioned.id,
post_id: None,
comment_id: Some(comment.id),
ap_url: ment.link_props.href_string().unwrap_or(String::new())
});
res.notify(conn);
res
})
}
}
}
impl Notify for Mention {
fn notify(&self, conn: &PgConnection) {
let author = self.get_comment(conn)
.map(|c| c.get_author(conn).display_name.clone())
.unwrap_or_else(|| self.get_post(conn).unwrap().get_authors(conn)[0].display_name.clone());
self.get_mentioned(conn).map(|m| {
Notification::insert(conn, NewNotification {
title: "{{ data }} mentioned you.".to_string(),
data: Some(author),
content: None,
link: Some(self.get_post(conn).map(|p| p.ap_url).unwrap_or_else(|| self.get_comment(conn).unwrap().ap_url.unwrap_or(String::new()))),
user_id: m.id
});
});
}
}
-73
View File
@@ -1,73 +0,0 @@
use diesel::{PgConnection, RunQueryDsl, select};
macro_rules! find_by {
($table:ident, $fn:ident, $($col:ident as $type:ident),+) => {
/// Try to find a $table with a given $col
pub fn $fn(conn: &PgConnection, $($col: $type),+) -> Option<Self> {
$table::table
$(.filter($table::$col.eq($col)))+
.limit(1)
.load::<Self>(conn)
.expect("Error loading $table by $col")
.into_iter().nth(0)
}
};
}
macro_rules! list_by {
($table:ident, $fn:ident, $($col:ident as $type:ident),+) => {
/// Try to find a $table with a given $col
pub fn $fn(conn: &PgConnection, $($col: $type),+) -> Vec<Self> {
$table::table
$(.filter($table::$col.eq($col)))+
.load::<Self>(conn)
.expect("Error loading $table by $col")
}
};
}
macro_rules! get {
($table:ident) => {
pub fn get(conn: &PgConnection, id: i32) -> Option<Self> {
$table::table.filter($table::id.eq(id))
.limit(1)
.load::<Self>(conn)
.expect("Error loading $table by id")
.into_iter().nth(0)
}
};
}
macro_rules! insert {
($table:ident, $from:ident) => {
pub fn insert(conn: &PgConnection, new: $from) -> Self {
diesel::insert_into($table::table)
.values(new)
.get_result(conn)
.expect("Error saving new $table")
}
};
}
sql_function!(nextval, nextval_t, (seq: ::diesel::sql_types::Text) -> ::diesel::sql_types::BigInt);
sql_function!(setval, setval_t, (seq: ::diesel::sql_types::Text, val: ::diesel::sql_types::BigInt) -> ::diesel::sql_types::BigInt);
fn get_next_id(conn: &PgConnection, seq: &str) -> i32 {
// We cant' use currval because it may fail if nextval have never been called before
let next = select(nextval(seq)).get_result::<i64>(conn).expect("Next ID fail");
select(setval(seq, next - 1)).get_result::<i64>(conn).expect("Reset ID fail");
next as i32
}
pub mod blog_authors;
pub mod blogs;
pub mod comments;
pub mod follows;
pub mod instance;
pub mod likes;
pub mod mentions;
pub mod notifications;
pub mod post_authors;
pub mod posts;
pub mod reshares;
pub mod users;
-38
View File
@@ -1,38 +0,0 @@
use chrono::NaiveDateTime;
use diesel::{self, PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods};
use models::users::User;
use schema::notifications;
#[derive(Queryable, Identifiable, Serialize)]
pub struct Notification {
pub id: i32,
pub title: String,
pub content: Option<String>,
pub link: Option<String>,
pub user_id: i32,
pub creation_date: NaiveDateTime,
pub data: Option<String>
}
#[derive(Insertable)]
#[table_name = "notifications"]
pub struct NewNotification {
pub title: String,
pub content: Option<String>,
pub link: Option<String>,
pub user_id: i32,
pub data: Option<String>
}
impl Notification {
insert!(notifications, NewNotification);
get!(notifications);
pub fn find_for_user(conn: &PgConnection, user: &User) -> Vec<Notification> {
notifications::table.filter(notifications::user_id.eq(user.id))
.order_by(notifications::creation_date.desc())
.load::<Notification>(conn)
.expect("Couldn't load user notifications")
}
}
-28
View File
@@ -1,28 +0,0 @@
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
use models::{
posts::Post,
users::User
};
use schema::post_authors;
#[derive(Queryable, Identifiable, Associations)]
#[belongs_to(Post)]
#[belongs_to(User, foreign_key = "author_id")]
pub struct PostAuthor {
pub id: i32,
pub post_id: i32,
pub author_id: i32
}
#[derive(Insertable)]
#[table_name = "post_authors"]
pub struct NewPostAuthor {
pub post_id: i32,
pub author_id: i32
}
impl PostAuthor {
insert!(post_authors, NewPostAuthor);
get!(post_authors);
}
-244
View File
@@ -1,244 +0,0 @@
use activitypub::{
activity::Create,
link,
object::Article
};
use chrono::{NaiveDateTime, TimeZone, Utc};
use diesel::{self, PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods, BelongingToDsl, dsl::any};
use heck::KebabCase;
use serde_json;
use BASE_URL;
use activity_pub::{
PUBLIC_VISIBILTY, ap_url, Id, IntoId,
inbox::FromActivity
};
use models::{
blogs::Blog,
instance::Instance,
likes::Like,
mentions::Mention,
post_authors::*,
reshares::Reshare,
users::User
};
use schema::posts;
use safe_string::SafeString;
#[derive(Queryable, Identifiable, Serialize, Clone)]
pub struct Post {
pub id: i32,
pub blog_id: i32,
pub slug: String,
pub title: String,
pub content: SafeString,
pub published: bool,
pub license: String,
pub creation_date: NaiveDateTime,
pub ap_url: String
}
#[derive(Insertable)]
#[table_name = "posts"]
pub struct NewPost {
pub blog_id: i32,
pub slug: String,
pub title: String,
pub content: SafeString,
pub published: bool,
pub license: String,
pub ap_url: String
}
impl Post {
insert!(posts, NewPost);
get!(posts);
find_by!(posts, find_by_slug, slug as String, blog_id as i32);
find_by!(posts, find_by_ap_url, ap_url as String);
pub fn count_local(conn: &PgConnection) -> usize {
use schema::post_authors;
use schema::users;
let local_authors = users::table.filter(users::instance_id.eq(Instance::local_id(conn))).select(users::id);
let local_posts_id = post_authors::table.filter(post_authors::author_id.eq(any(local_authors))).select(post_authors::post_id);
posts::table.filter(posts::id.eq(any(local_posts_id)))
.load::<Post>(conn)
.expect("Couldn't load local posts")
.len()
}
pub fn get_recents(conn: &PgConnection, limit: i64) -> Vec<Post> {
posts::table.order(posts::creation_date.desc())
.limit(limit)
.load::<Post>(conn)
.expect("Error loading recent posts")
}
pub fn get_recents_for_author(conn: &PgConnection, author: &User, limit: i64) -> Vec<Post> {
use schema::post_authors;
let posts = PostAuthor::belonging_to(author).select(post_authors::post_id);
posts::table.filter(posts::id.eq(any(posts)))
.order(posts::creation_date.desc())
.limit(limit)
.load::<Post>(conn)
.expect("Error loading recent posts for author")
}
pub fn get_recents_for_blog(conn: &PgConnection, blog: &Blog, limit: i64) -> Vec<Post> {
posts::table.filter(posts::blog_id.eq(blog.id))
.order(posts::creation_date.desc())
.limit(limit)
.load::<Post>(conn)
.expect("Error loading recent posts for blog")
}
pub fn get_authors(&self, conn: &PgConnection) -> Vec<User> {
use schema::users;
use schema::post_authors;
let author_list = PostAuthor::belonging_to(self).select(post_authors::author_id);
users::table.filter(users::id.eq(any(author_list))).load::<User>(conn).unwrap()
}
pub fn get_blog(&self, conn: &PgConnection) -> Blog {
use schema::blogs;
blogs::table.filter(blogs::id.eq(self.blog_id))
.limit(1)
.load::<Blog>(conn)
.expect("Couldn't load blog associted to post")
.into_iter().nth(0).unwrap()
}
pub fn get_likes(&self, conn: &PgConnection) -> Vec<Like> {
use schema::likes;
likes::table.filter(likes::post_id.eq(self.id))
.load::<Like>(conn)
.expect("Couldn't load likes associted to post")
}
pub fn get_reshares(&self, conn: &PgConnection) -> Vec<Reshare> {
use schema::reshares;
reshares::table.filter(reshares::post_id.eq(self.id))
.load::<Reshare>(conn)
.expect("Couldn't load reshares associted to post")
}
pub fn update_ap_url(&self, conn: &PgConnection) -> Post {
if self.ap_url.len() == 0 {
diesel::update(self)
.set(posts::ap_url.eq(self.compute_id(conn)))
.get_result::<Post>(conn).expect("Couldn't update AP URL")
} else {
self.clone()
}
}
pub fn get_receivers_urls(&self, conn: &PgConnection) -> Vec<String> {
let followers = self.get_authors(conn).into_iter().map(|a| a.get_followers(conn)).collect::<Vec<Vec<User>>>();
let to = followers.into_iter().fold(vec![], |mut acc, f| {
for x in f {
acc.push(x.ap_url);
}
acc
});
to
}
pub fn into_activity(&self, conn: &PgConnection) -> Article {
let mut to = self.get_receivers_urls(conn);
to.push(PUBLIC_VISIBILTY.to_string());
let mentions = Mention::list_for_post(conn, self.id).into_iter().map(|m| m.to_activity(conn)).collect::<Vec<link::Mention>>();
let mut article = Article::default();
article.object_props.set_name_string(self.title.clone()).expect("Article::into_activity: name error");
article.object_props.set_id_string(self.ap_url.clone()).expect("Article::into_activity: id error");
article.object_props.set_attributed_to_link_vec::<Id>(self.get_authors(conn).into_iter().map(|x| Id::new(x.ap_url)).collect()).expect("Article::into_activity: attributedTo error");
article.object_props.set_content_string(self.content.get().clone()).expect("Article::into_activity: content error");
article.object_props.set_published_utctime(Utc.from_utc_datetime(&self.creation_date)).expect("Article::into_activity: published error");
article.object_props.set_tag_link_vec(mentions).expect("Article::into_activity: tag error");
article.object_props.set_url_string(self.ap_url.clone()).expect("Article::into_activity: url error");
article.object_props.set_to_link_vec::<Id>(to.into_iter().map(Id::new).collect()).expect("Article::into_activity: to error");
article.object_props.set_cc_link_vec::<Id>(vec![]).expect("Article::into_activity: cc error");
article
}
pub fn create_activity(&self, conn: &PgConnection) -> Create {
let article = self.into_activity(conn);
let mut act = Create::default();
act.object_props.set_id_string(format!("{}/activity", self.ap_url)).expect("Article::create_activity: id error");
act.object_props.set_to_link_vec::<Id>(article.object_props.to_link_vec().expect("Article::create_activity: Couldn't copy 'to'"))
.expect("Article::create_activity: to error");
act.object_props.set_cc_link_vec::<Id>(article.object_props.cc_link_vec().expect("Article::create_activity: Couldn't copy 'cc'"))
.expect("Article::create_activity: cc error");
act.create_props.set_actor_link(Id::new(self.get_authors(conn)[0].clone().ap_url)).expect("Article::create_activity: actor error");
act.create_props.set_object_object(article).expect("Article::create_activity: object error");
act
}
pub fn to_json(&self, conn: &PgConnection) -> serde_json::Value {
json!({
"post": self,
"author": self.get_authors(conn)[0].to_json(conn),
"url": format!("/~/{}/{}/", self.get_blog(conn).actor_id, self.slug),
"date": self.creation_date.timestamp()
})
}
pub fn compute_id(&self, conn: &PgConnection) -> String {
ap_url(format!("{}/~/{}/{}/", BASE_URL.as_str(), self.get_blog(conn).actor_id, self.slug))
}
}
impl FromActivity<Article> for Post {
fn from_activity(conn: &PgConnection, article: Article, _actor: Id) -> Post {
let (blog, authors) = article.object_props.attributed_to_link_vec::<Id>()
.expect("Post::from_activity: attributedTo error")
.into_iter()
.fold((None, vec![]), |(blog, mut authors), link| {
let url: String = link.into();
match User::from_url(conn, url.clone()) {
Some(user) => {
authors.push(user);
(blog, authors)
},
None => (blog.or_else(|| Blog::from_url(conn, url)), authors)
}
});
let title = article.object_props.name_string().expect("Post::from_activity: title error");
let post = Post::insert(conn, NewPost {
blog_id: blog.expect("Received a new Article without a blog").id,
slug: title.to_kebab_case(),
title: title,
content: SafeString::new(&article.object_props.content_string().expect("Post::from_activity: content error")),
published: true,
license: String::from("CC-0"), // TODO
// FIXME: This is wrong: with this logic, we may use the display URL as the AP ID. We need two different fields
ap_url: article.object_props.url_string().unwrap_or(article.object_props.id_string().expect("Post::from_activity: url + id error"))
});
for author in authors.into_iter() {
PostAuthor::insert(conn, NewPostAuthor {
post_id: post.id,
author_id: author.id
});
}
// save mentions
if let Some(serde_json::Value::Array(tags)) = article.object_props.tag.clone() {
for tag in tags.into_iter() {
serde_json::from_value::<link::Mention>(tag)
.map(|m| Mention::from_activity(conn, m, post.id, true))
.ok();
}
}
post
}
}
impl IntoId for Post {
fn into_id(self) -> Id {
Id::new(self.ap_url.clone())
}
}
-121
View File
@@ -1,121 +0,0 @@
use activitypub::activity::{Announce, Undo};
use chrono::NaiveDateTime;
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
use activity_pub::{Id, IntoId, inbox::{FromActivity, Notify, Deletable}, PUBLIC_VISIBILTY};
use models::{notifications::*, posts::Post, users::User};
use schema::reshares;
#[derive(Serialize, Deserialize, Queryable, Identifiable)]
pub struct Reshare {
pub id: i32,
pub user_id: i32,
pub post_id: i32,
pub ap_url: String,
pub creation_date: NaiveDateTime
}
#[derive(Insertable)]
#[table_name = "reshares"]
pub struct NewReshare {
pub user_id: i32,
pub post_id: i32,
pub ap_url: String
}
impl Reshare {
insert!(reshares, NewReshare);
get!(reshares);
find_by!(reshares, find_by_ap_url, ap_url as String);
find_by!(reshares, find_by_user_on_post, user_id as i32, post_id as i32);
pub fn update_ap_url(&self, conn: &PgConnection) {
if self.ap_url.len() == 0 {
diesel::update(self)
.set(reshares::ap_url.eq(format!(
"{}/reshare/{}",
User::get(conn, self.user_id).unwrap().ap_url,
Post::get(conn, self.post_id).unwrap().ap_url
)))
.get_result::<Reshare>(conn).expect("Couldn't update AP URL");
}
}
pub fn get_recents_for_author(conn: &PgConnection, user: &User, limit: i64) -> Vec<Reshare> {
reshares::table.filter(reshares::user_id.eq(user.id))
.order(reshares::creation_date.desc())
.limit(limit)
.load::<Reshare>(conn)
.expect("Error loading recent reshares for user")
}
pub fn get_post(&self, conn: &PgConnection) -> Option<Post> {
Post::get(conn, self.post_id)
}
pub fn delete(&self, conn: &PgConnection) -> Undo {
diesel::delete(self).execute(conn).unwrap();
let mut act = Undo::default();
act.undo_props.set_actor_link(User::get(conn, self.user_id).unwrap().into_id()).unwrap();
act.undo_props.set_object_object(self.into_activity(conn)).unwrap();
act.object_props.set_id_string(format!("{}#delete", self.ap_url)).expect("Reshare::delete: id error");
act.object_props.set_to_link(Id::new(PUBLIC_VISIBILTY.to_string())).expect("Reshare::delete: to error");
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Reshare::delete: cc error");
act
}
pub fn into_activity(&self, conn: &PgConnection) -> Announce {
let mut act = Announce::default();
act.announce_props.set_actor_link(User::get(conn, self.user_id).unwrap().into_id()).unwrap();
act.announce_props.set_object_link(Post::get(conn, self.post_id).unwrap().into_id()).unwrap();
act.object_props.set_id_string(self.ap_url.clone()).unwrap();
act.object_props.set_to_link(Id::new(PUBLIC_VISIBILTY.to_string())).expect("Reshare::into_activity: to error");
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Reshare::into_activity: cc error");
act
}
}
impl FromActivity<Announce> for Reshare {
fn from_activity(conn: &PgConnection, announce: Announce, _actor: Id) -> Reshare {
let user = User::from_url(conn, announce.announce_props.actor.as_str().unwrap().to_string());
let post = Post::find_by_ap_url(conn, announce.announce_props.object.as_str().unwrap().to_string());
let reshare = Reshare::insert(conn, NewReshare {
post_id: post.unwrap().id,
user_id: user.unwrap().id,
ap_url: announce.object_props.id_string().unwrap_or(String::from(""))
});
reshare.notify(conn);
reshare
}
}
impl Notify for Reshare {
fn notify(&self, conn: &PgConnection) {
let actor = User::get(conn, self.user_id).unwrap();
let post = self.get_post(conn).unwrap();
for author in post.get_authors(conn) {
let post = post.clone();
Notification::insert(conn, NewNotification {
title: "{{ data }} reshared your article".to_string(),
data: Some(actor.display_name.clone()),
content: Some(post.title),
link: Some(post.ap_url),
user_id: author.id
});
}
}
}
impl Deletable for Reshare {
fn delete_activity(conn: &PgConnection, id: Id) -> bool {
if let Some(reshare) = Reshare::find_by_ap_url(conn, id.into()) {
reshare.delete(conn);
true
} else {
false
}
}
}
-464
View File
@@ -1,464 +0,0 @@
use activitypub::{
Actor, Object, Endpoint, CustomObject,
actor::Person,
collection::OrderedCollection
};
use bcrypt;
use chrono::NaiveDateTime;
use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods, BelongingToDsl, PgConnection, dsl::any};
use openssl::{
hash::MessageDigest,
pkey::{PKey, Private},
rsa::Rsa,
sign
};
use reqwest::{
Client,
header::{Accept, qitem},
mime::Mime
};
use rocket::{
request::{self, FromRequest, Request},
outcome::IntoOutcome
};
use serde_json;
use url::Url;
use webfinger::*;
use BASE_URL;
use activity_pub::{
ap_url, ActivityStream, Id, IntoId, ApSignature, PublicKey,
inbox::{Inbox, WithInbox},
sign::{Signer, gen_keypair}
};
use db_conn::DbConn;
use models::{
blogs::Blog,
blog_authors::BlogAuthor,
follows::Follow,
instance::*,
post_authors::PostAuthor,
posts::Post
};
use schema::users;
use safe_string::SafeString;
pub const AUTH_COOKIE: &'static str = "user_id";
pub type CustomPerson = CustomObject<ApSignature, Person>;
#[derive(Queryable, Identifiable, Serialize, Deserialize, Clone, Debug)]
pub struct User {
pub id: i32,
pub username: String,
pub display_name: String,
pub outbox_url: String,
pub inbox_url: String,
pub is_admin: bool,
pub summary: SafeString,
pub email: Option<String>,
pub hashed_password: Option<String>,
pub instance_id: i32,
pub creation_date: NaiveDateTime,
pub ap_url: String,
pub private_key: Option<String>,
pub public_key: String,
pub shared_inbox_url: Option<String>
}
#[derive(Insertable)]
#[table_name = "users"]
pub struct NewUser {
pub username: String,
pub display_name: String,
pub outbox_url: String,
pub inbox_url: String,
pub is_admin: bool,
pub summary: SafeString,
pub email: Option<String>,
pub hashed_password: Option<String>,
pub instance_id: i32,
pub ap_url: String,
pub private_key: Option<String>,
pub public_key: String,
pub shared_inbox_url: Option<String>
}
const USER_PREFIX: &'static str = "@";
impl User {
insert!(users, NewUser);
get!(users);
find_by!(users, find_by_email, email as String);
find_by!(users, find_by_name, username as String, instance_id as i32);
find_by!(users, find_by_ap_url, ap_url as String);
pub fn get_instance(&self, conn: &PgConnection) -> Instance {
Instance::get(conn, self.instance_id).expect("Couldn't find instance")
}
pub fn grant_admin_rights(&self, conn: &PgConnection) {
diesel::update(self)
.set(users::is_admin.eq(true))
.load::<User>(conn)
.expect("Couldn't grant admin rights");
}
pub fn update(&self, conn: &PgConnection, name: String, email: String, summary: String) -> User {
diesel::update(self)
.set((
users::display_name.eq(name),
users::email.eq(email),
users::summary.eq(summary),
)).load::<User>(conn)
.expect("Couldn't update user")
.into_iter().nth(0).unwrap()
}
pub fn count_local(conn: &PgConnection) -> usize {
users::table.filter(users::instance_id.eq(Instance::local_id(conn)))
.load::<User>(conn)
.expect("Couldn't load local users")
.len()
}
pub fn find_local(conn: &PgConnection, username: String) -> Option<User> {
User::find_by_name(conn, username, Instance::local_id(conn))
}
pub fn find_by_fqn(conn: &PgConnection, fqn: String) -> Option<User> {
if fqn.contains("@") { // remote user
match Instance::find_by_domain(conn, String::from(fqn.split("@").last().unwrap())) {
Some(instance) => {
match User::find_by_name(conn, String::from(fqn.split("@").nth(0).unwrap()), instance.id) {
Some(u) => Some(u),
None => User::fetch_from_webfinger(conn, fqn)
}
},
None => User::fetch_from_webfinger(conn, fqn)
}
} else { // local user
User::find_local(conn, fqn)
}
}
fn fetch_from_webfinger(conn: &PgConnection, acct: String) -> Option<User> {
match resolve(acct.clone()) {
Ok(wf) => wf.links.into_iter().find(|l| l.mime_type == Some(String::from("application/activity+json"))).and_then(|l| User::fetch_from_url(conn, l.href)),
Err(details) => {
println!("{:?}", details);
None
}
}
}
fn fetch_from_url(conn: &PgConnection, url: String) -> Option<User> {
let req = Client::new()
.get(&url[..])
.header(Accept(vec![qitem("application/activity+json".parse::<Mime>().unwrap())]))
.send();
match req {
Ok(mut res) => {
let text = &res.text().unwrap();
let ap_sign: ApSignature = serde_json::from_str(text).unwrap();
let mut json: CustomPerson = serde_json::from_str(text).unwrap();
json.custom_props = ap_sign; // without this workaround, publicKey is not correctly deserialized
Some(User::from_activity(conn, json, Url::parse(url.as_ref()).unwrap().host_str().unwrap().to_string()))
},
Err(_) => None
}
}
fn from_activity(conn: &PgConnection, acct: CustomPerson, inst: String) -> User {
let instance = match Instance::find_by_domain(conn, inst.clone()) {
Some(instance) => instance,
None => {
Instance::insert(conn, NewInstance {
name: inst.clone(),
public_domain: inst.clone(),
local: false
})
}
};
println!("User from act : {:?}", acct.custom_props);
User::insert(conn, NewUser {
username: acct.object.ap_actor_props.preferred_username_string().expect("User::from_activity: preferredUsername error"),
display_name: acct.object.object_props.name_string().expect("User::from_activity: name error"),
outbox_url: acct.object.ap_actor_props.outbox_string().expect("User::from_activity: outbox error"),
inbox_url: acct.object.ap_actor_props.inbox_string().expect("User::from_activity: inbox error"),
is_admin: false,
summary: SafeString::new(&acct.object.object_props.summary_string().expect("User::from_activity: summary error")),
email: None,
hashed_password: None,
instance_id: instance.id,
ap_url: acct.object.object_props.id_string().expect("User::from_activity: id error"),
public_key: acct.custom_props.public_key_publickey().expect("User::from_activity: publicKey error")
.public_key_pem_string().expect("User::from_activity: publicKey.publicKeyPem error"),
private_key: None,
shared_inbox_url: acct.object.ap_actor_props.endpoints_endpoint()
.and_then(|e| e.shared_inbox_string()).ok()
})
}
pub fn hash_pass(pass: String) -> String {
bcrypt::hash(pass.as_str(), bcrypt::DEFAULT_COST).unwrap()
}
pub fn auth(&self, pass: String) -> bool {
bcrypt::verify(pass.as_str(), self.hashed_password.clone().unwrap().as_str()).is_ok()
}
pub fn update_boxes(&self, conn: &PgConnection) {
let instance = self.get_instance(conn);
if self.outbox_url.len() == 0 {
diesel::update(self)
.set(users::outbox_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "outbox")))
.get_result::<User>(conn).expect("Couldn't update outbox URL");
}
if self.inbox_url.len() == 0 {
diesel::update(self)
.set(users::inbox_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "inbox")))
.get_result::<User>(conn).expect("Couldn't update inbox URL");
}
if self.ap_url.len() == 0 {
diesel::update(self)
.set(users::ap_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "")))
.get_result::<User>(conn).expect("Couldn't update AP URL");
}
if self.shared_inbox_url.is_none() {
diesel::update(self)
.set(users::shared_inbox_url.eq(ap_url(format!("{}/inbox", Instance::get_local(conn).unwrap().public_domain))))
.get_result::<User>(conn).expect("Couldn't update shared inbox URL");
}
}
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<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| {
serde_json::to_value(p.create_activity(conn)).unwrap()
}).collect::<Vec<serde_json::Value>>()
}
pub fn get_fqn(&self, conn: &PgConnection) -> String {
if self.instance_id == Instance::local_id(conn) {
self.username.clone()
} else {
format!("{}@{}", self.username, self.get_instance(conn).public_domain)
}
}
pub fn get_followers(&self, conn: &PgConnection) -> Vec<User> {
use schema::follows;
let follows = Follow::belonging_to(self).select(follows::follower_id);
users::table.filter(users::id.eq(any(follows))).load::<User>(conn).unwrap()
}
pub fn get_following(&self, conn: &PgConnection) -> Vec<User> {
use schema::follows;
let follows = follows::table.filter(follows::follower_id.eq(self.id)).select(follows::following_id);
users::table.filter(users::id.eq(any(follows))).load::<User>(conn).unwrap()
}
pub fn is_following(&self, conn: &PgConnection, other_id: i32) -> bool {
use schema::follows;
follows::table
.filter(follows::follower_id.eq(other_id))
.filter(follows::following_id.eq(self.id))
.load::<Follow>(conn)
.expect("Couldn't load follow relationship")
.len() > 0
}
pub fn has_liked(&self, conn: &PgConnection, post: &Post) -> bool {
use schema::likes;
use models::likes::Like;
likes::table
.filter(likes::post_id.eq(post.id))
.filter(likes::user_id.eq(self.id))
.load::<Like>(conn)
.expect("Couldn't load likes")
.len() > 0
}
pub fn has_reshared(&self, conn: &PgConnection, post: &Post) -> bool {
use schema::reshares;
use models::reshares::Reshare;
reshares::table
.filter(reshares::post_id.eq(post.id))
.filter(reshares::user_id.eq(self.id))
.load::<Reshare>(conn)
.expect("Couldn't load reshares")
.len() > 0
}
pub fn is_author_in(&self, conn: &PgConnection, blog: Blog) -> bool {
use schema::blog_authors;
blog_authors::table.filter(blog_authors::author_id.eq(self.id))
.filter(blog_authors::blog_id.eq(blog.id))
.load::<BlogAuthor>(conn)
.expect("Couldn't load blog/author relationship")
.len() > 0
}
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) -> CustomPerson {
let mut actor = Person::default();
actor.object_props.set_id_string(self.ap_url.clone()).expect("User::into_activity: id error");
actor.object_props.set_name_string(self.display_name.clone()).expect("User::into_activity: name error");
actor.object_props.set_summary_string(self.summary.get().clone()).expect("User::into_activity: summary error");
actor.object_props.set_url_string(self.ap_url.clone()).expect("User::into_activity: url error");
actor.ap_actor_props.set_inbox_string(self.inbox_url.clone()).expect("User::into_activity: inbox error");
actor.ap_actor_props.set_outbox_string(self.outbox_url.clone()).expect("User::into_activity: outbox error");
actor.ap_actor_props.set_preferred_username_string(self.username.clone()).expect("User::into_activity: preferredUsername error");
let mut endpoints = Endpoint::default();
endpoints.set_shared_inbox_string(ap_url(format!("{}/inbox/", BASE_URL.as_str()))).expect("User::into_activity: endpoints.sharedInbox error");
actor.ap_actor_props.set_endpoints_endpoint(endpoints).expect("User::into_activity: endpoints error");
let mut public_key = PublicKey::default();
public_key.set_id_string(format!("{}#main-key", self.ap_url)).expect("User::into_activity: publicKey.id error");
public_key.set_owner_string(self.ap_url.clone()).expect("User::into_activity: publicKey.owner error");
public_key.set_public_key_pem_string(self.public_key.clone()).expect("User::into_activity: publicKey.publicKeyPem error");
let mut ap_signature = ApSignature::default();
ap_signature.set_public_key_publickey(public_key).expect("User::into_activity: publicKey error");
CustomPerson::new(actor, ap_signature)
}
pub fn to_json(&self, conn: &PgConnection) -> serde_json::Value {
let mut json = serde_json::to_value(self).unwrap();
json["fqn"] = serde_json::Value::String(self.get_fqn(conn));
json
}
pub fn webfinger(&self, conn: &PgConnection) -> Webfinger {
Webfinger {
subject: format!("acct:{}@{}", self.username, self.get_instance(conn).public_domain),
aliases: vec![self.ap_url.clone()],
links: vec![
Link {
rel: String::from("http://webfinger.net/rel/profile-page"),
mime_type: None,
href: self.ap_url.clone()
},
Link {
rel: String::from("http://schemas.google.com/g/2010#updates-from"),
mime_type: Some(String::from("application/atom+xml")),
href: self.get_instance(conn).compute_box(USER_PREFIX, self.username.clone(), "feed.atom")
},
Link {
rel: String::from("self"),
mime_type: Some(String::from("application/activity+json")),
href: self.ap_url.clone()
}
]
}
}
pub fn from_url(conn: &PgConnection, url: String) -> Option<User> {
User::find_by_ap_url(conn, url.clone()).or_else(|| {
// The requested user was not in the DB
// We try to fetch it if it is remote
if Url::parse(url.as_ref()).unwrap().host_str().unwrap() != BASE_URL.as_str() {
User::fetch_from_url(conn, url)
} else {
None
}
})
}
}
impl<'a, 'r> FromRequest<'a, 'r> for User {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<User, ()> {
let conn = request.guard::<DbConn>()?;
request.cookies()
.get_private(AUTH_COOKIE)
.and_then(|cookie| cookie.value().parse().ok())
.map(|id| User::get(&*conn, id).unwrap())
.or_forward(())
}
}
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 {}
impl Signer for User {
fn get_key_id(&self) -> String {
format!("{}#main-key", self.ap_url)
}
fn sign(&self, to_sign: String) -> Vec<u8> {
let key = self.get_keypair();
let mut signer = sign::Signer::new(MessageDigest::sha256(), &key).unwrap();
signer.update(to_sign.as_bytes()).unwrap();
signer.sign_to_vec().unwrap()
}
}
impl NewUser {
/// Creates a new local user
pub fn new_local(
conn: &PgConnection,
username: String,
display_name: String,
is_admin: bool,
summary: String,
email: String,
password: String
) -> User {
let (pub_key, priv_key) = gen_keypair();
User::insert(conn, NewUser {
username: username,
display_name: display_name,
outbox_url: String::from(""),
inbox_url: String::from(""),
is_admin: is_admin,
summary: SafeString::new(&summary),
email: Some(email),
hashed_password: Some(password),
instance_id: Instance::local_id(conn),
ap_url: String::from(""),
public_key: String::from_utf8(pub_key).unwrap(),
private_key: Some(String::from_utf8(priv_key).unwrap()),
shared_inbox_url: None
})
}
}
+4 -4
View File
@@ -6,16 +6,16 @@ use rocket::{
use rocket_contrib::Template;
use serde_json;
use activity_pub::ActivityStream;
use db_conn::DbConn;
use models::{
use plume_common::activity_pub::ActivityStream;
use plume_common::utils;
use plume_models::{
blog_authors::*,
blogs::*,
db_conn::DbConn,
instance::Instance,
posts::Post,
users::User
};
use utils;
#[get("/~/<name>", rank = 2)]
fn details(name: String, conn: DbConn, user: Option<User>) -> Template {
+4 -3
View File
@@ -4,15 +4,16 @@ use rocket::{
};
use serde_json;
use activity_pub::{broadcast, inbox::Inbox};
use db_conn::DbConn;
use models::{
use plume_common::activity_pub::broadcast;
use plume_models::{
blogs::Blog,
comments::*,
db_conn::DbConn,
instance::Instance,
posts::Post,
users::User
};
use inbox::Inbox;
#[derive(FromForm)]
pub struct CommentQuery {
+1 -1
View File
@@ -1,7 +1,7 @@
use rocket_contrib::Template;
use rocket::Request;
use rocket::request::FromRequest;
use models::users::User;
use plume_models::users::User;
#[catch(404)]
fn not_found(req: &Request) -> Template {
+3 -3
View File
@@ -2,14 +2,14 @@ use gettextrs::gettext;
use rocket_contrib::{Json, Template};
use serde_json;
use activity_pub::inbox::Inbox;
use db_conn::DbConn;
use models::{
use plume_models::{
comments::Comment,
db_conn::DbConn,
posts::Post,
users::User,
instance::*
};
use inbox::Inbox;
#[get("/")]
fn index(conn: DbConn, user: Option<User>) -> Template {
+4 -5
View File
@@ -1,16 +1,15 @@
use rocket::response::{Redirect, Flash};
use activity_pub::{broadcast, inbox::Notify};
use db_conn::DbConn;
use models::{
use plume_common::activity_pub::{broadcast, inbox::Notify};
use plume_common::utils;
use plume_models::{
blogs::Blog,
db_conn::DbConn,
likes,
posts::Post,
users::User
};
use utils;
#[get("/~/<blog>/<slug>/like")]
fn create(blog: String, slug: String, user: User, conn: DbConn) -> Redirect {
let b = Blog::find_by_fqn(&*conn, blog.clone()).unwrap();
+2 -4
View File
@@ -1,10 +1,8 @@
use rocket::response::{Redirect, Flash};
use rocket_contrib::Template;
use db_conn::DbConn;
use models::{notifications::Notification, users::User};
use utils;
use plume_common::utils;
use plume_models::{db_conn::DbConn, notifications::Notification, users::User};
#[get("/notifications")]
fn notifications(conn: DbConn, user: User) -> Template {
+5 -5
View File
@@ -5,19 +5,19 @@ use rocket::response::{Redirect, Flash};
use rocket_contrib::Template;
use serde_json;
use activity_pub::{broadcast, ActivityStream};
use db_conn::DbConn;
use models::{
use plume_common::activity_pub::{broadcast, ActivityStream};
use plume_common::utils;
use plume_models::{
blogs::*,
db_conn::DbConn,
comments::Comment,
mentions::Mention,
post_authors::*,
posts::*,
safe_string::SafeString,
users::User
};
use routes::comments::CommentQuery;
use safe_string::SafeString;
use utils;
// See: https://github.com/SergioBenitez/Rocket/pull/454
#[get("/~/<blog>/<slug>", rank = 4)]
+4 -5
View File
@@ -1,16 +1,15 @@
use rocket::response::{Redirect, Flash};
use activity_pub::{broadcast, inbox::Notify};
use db_conn::DbConn;
use models::{
use plume_common::activity_pub::{broadcast, inbox::Notify};
use plume_common::utils;
use plume_models::{
blogs::Blog,
db_conn::DbConn,
posts::Post,
reshares::*,
users::User
};
use utils;
#[get("/~/<blog>/<slug>/reshare")]
fn create(blog: String, slug: String, user: User, conn: DbConn) -> Redirect {
let b = Blog::find_by_fqn(&*conn, blog.clone()).unwrap();
+4 -2
View File
@@ -6,8 +6,10 @@ use rocket::{
};
use rocket_contrib::Template;
use db_conn::DbConn;
use models::users::{User, AUTH_COOKIE};
use plume_models::{
db_conn::DbConn,
users::{User, AUTH_COOKIE}
};
#[get("/login")]
fn new(user: Option<User>) -> Template {
+6 -5
View File
@@ -8,20 +8,21 @@ use rocket::{request::Form,
use rocket_contrib::Template;
use serde_json;
use activity_pub::{
use plume_common::activity_pub::{
ActivityStream, broadcast, Id, IntoId,
inbox::{Inbox, Notify}
inbox::{Notify}
};
use db_conn::DbConn;
use models::{
use plume_common::utils;
use plume_models::{
blogs::Blog,
db_conn::DbConn,
follows,
instance::Instance,
posts::Post,
reshares::Reshare,
users::*
};
use utils;
use inbox::Inbox;
#[get("/me")]
fn me(user: Option<User>) -> Result<Redirect, Flash<Redirect>> {
+2 -4
View File
@@ -3,10 +3,8 @@ use rocket::response::Content;
use serde_json;
use webfinger::*;
use BASE_URL;
use activity_pub::ap_url;
use db_conn::DbConn;
use models::{blogs::Blog, users::User};
use plume_common::activity_pub::ap_url;
use plume_models::{BASE_URL, db_conn::DbConn, blogs::Blog, users::User};
#[get("/.well-known/nodeinfo")]
fn nodeinfo() -> Content<String> {
-103
View File
@@ -1,103 +0,0 @@
use ammonia::clean;
use serde::{self, Serialize, Deserialize,
Serializer, Deserializer, de::Visitor};
use std::{fmt::{self, Display},
borrow::Borrow, io::Write,
ops::Deref};
use diesel::{self, deserialize::Queryable,
types::ToSql,
sql_types::Text,
serialize::{self, Output}};
#[derive(Debug, Clone, AsExpression, FromSqlRow, Default)]
#[sql_type = "Text"]
pub struct SafeString{
value: String,
}
impl SafeString{
pub fn new(value: &str) -> Self {
SafeString{
value: clean(&value),
}
}
pub fn set(&mut self, value: &str) {
self.value = clean(value);
}
pub fn get(&self) -> &String {
&self.value
}
}
impl Serialize for SafeString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer, {
serializer.serialize_str(&self.value)
}
}
struct SafeStringVisitor;
impl<'de> Visitor<'de> for SafeStringVisitor {
type Value = SafeString;
fn expecting(&self, formatter:&mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string")
}
fn visit_str<E>(self, value: &str) -> Result<SafeString, E>
where E: serde::de::Error{
Ok(SafeString::new(value))
}
}
impl<'de> Deserialize<'de> for SafeString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>, {
Ok(
deserializer.deserialize_string(SafeStringVisitor)?
)
}
}
impl Queryable<Text, diesel::pg::Pg> for SafeString {
type Row = String;
fn build(value: Self::Row) -> Self {
SafeString::new(&value)
}
}
impl<DB> ToSql<diesel::sql_types::Text, DB> for SafeString
where
DB: diesel::backend::Backend,
str: ToSql<diesel::sql_types::Text, DB>, {
fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
str::to_sql(&self.value, out)
}
}
impl Borrow<str> for SafeString {
fn borrow(&self) -> &str {
&self.value
}
}
impl Display for SafeString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}
impl Deref for SafeString {
type Target = str;
fn deref(&self) -> &str {
&self.value
}
}
impl AsRef<str> for SafeString {
fn as_ref(&self) -> &str {
&self.value
}
}
-174
View File
@@ -1,174 +0,0 @@
table! {
blog_authors (id) {
id -> Int4,
blog_id -> Int4,
author_id -> Int4,
is_owner -> Bool,
}
}
table! {
blogs (id) {
id -> Int4,
actor_id -> Varchar,
title -> Varchar,
summary -> Text,
outbox_url -> Varchar,
inbox_url -> Varchar,
instance_id -> Int4,
creation_date -> Timestamp,
ap_url -> Text,
private_key -> Nullable<Text>,
public_key -> Text,
}
}
table! {
comments (id) {
id -> Int4,
content -> Text,
in_response_to_id -> Nullable<Int4>,
post_id -> Int4,
author_id -> Int4,
creation_date -> Timestamp,
ap_url -> Nullable<Varchar>,
sensitive -> Bool,
spoiler_text -> Text,
}
}
table! {
follows (id) {
id -> Int4,
follower_id -> Int4,
following_id -> Int4,
}
}
table! {
instances (id) {
id -> Int4,
public_domain -> Varchar,
name -> Varchar,
local -> Bool,
blocked -> Bool,
creation_date -> Timestamp,
}
}
table! {
likes (id) {
id -> Int4,
user_id -> Int4,
post_id -> Int4,
creation_date -> Timestamp,
ap_url -> Varchar,
}
}
table! {
mentions (id) {
id -> Int4,
mentioned_id -> Int4,
post_id -> Nullable<Int4>,
comment_id -> Nullable<Int4>,
ap_url -> Varchar,
}
}
table! {
notifications (id) {
id -> Int4,
title -> Varchar,
content -> Nullable<Text>,
link -> Nullable<Varchar>,
user_id -> Int4,
creation_date -> Timestamp,
data -> Nullable<Varchar>,
}
}
table! {
post_authors (id) {
id -> Int4,
post_id -> Int4,
author_id -> Int4,
}
}
table! {
posts (id) {
id -> Int4,
blog_id -> Int4,
slug -> Varchar,
title -> Varchar,
content -> Text,
published -> Bool,
license -> Varchar,
creation_date -> Timestamp,
ap_url -> Varchar,
}
}
table! {
reshares (id) {
id -> Int4,
user_id -> Int4,
post_id -> Int4,
ap_url -> Varchar,
creation_date -> Timestamp,
}
}
table! {
users (id) {
id -> Int4,
username -> Varchar,
display_name -> Varchar,
outbox_url -> Varchar,
inbox_url -> Varchar,
is_admin -> Bool,
summary -> Text,
email -> Nullable<Text>,
hashed_password -> Nullable<Text>,
instance_id -> Int4,
creation_date -> Timestamp,
ap_url -> Text,
private_key -> Nullable<Text>,
public_key -> Text,
shared_inbox_url -> Nullable<Varchar>,
}
}
joinable!(blog_authors -> blogs (blog_id));
joinable!(blog_authors -> users (author_id));
joinable!(blogs -> instances (instance_id));
joinable!(comments -> posts (post_id));
joinable!(comments -> users (author_id));
joinable!(likes -> posts (post_id));
joinable!(likes -> users (user_id));
joinable!(mentions -> comments (comment_id));
joinable!(mentions -> posts (post_id));
joinable!(mentions -> users (mentioned_id));
joinable!(notifications -> users (user_id));
joinable!(post_authors -> posts (post_id));
joinable!(post_authors -> users (author_id));
joinable!(posts -> blogs (blog_id));
joinable!(reshares -> posts (post_id));
joinable!(reshares -> users (user_id));
joinable!(users -> instances (instance_id));
allow_tables_to_appear_in_same_query!(
blog_authors,
blogs,
comments,
follows,
instances,
likes,
mentions,
notifications,
post_authors,
posts,
reshares,
users,
);
+6 -6
View File
@@ -7,12 +7,12 @@ use std::path::Path;
use std::process::{exit, Command};
use rpassword;
use DB_URL;
use db_conn::DbConn;
use models::instance::*;
use models::users::*;
pub type PgPool = Pool<ConnectionManager<PgConnection>>;
use plume_models::{
DB_URL,
db_conn::{DbConn, PgPool},
instance::*,
users::*
};
/// Initializes a database pool.
fn init_pool() -> Option<PgPool> {
-70
View File
@@ -1,70 +0,0 @@
use gettextrs::gettext;
use heck::CamelCase;
use pulldown_cmark::{Event, Parser, Options, Tag, html};
use rocket::{
http::uri::Uri,
response::{Redirect, Flash}
};
/// Remove non alphanumeric characters and CamelCase a string
pub fn make_actor_id(name: String) -> String {
name.as_str()
.to_camel_case()
.to_string()
.chars()
.filter(|c| c.is_alphanumeric())
.collect()
}
pub fn requires_login(message: &str, url: Uri) -> Flash<Redirect> {
Flash::new(Redirect::to(Uri::new(format!("/login?m={}", gettext(message.to_string())))), "callback", url.as_str())
}
/// Returns (HTML, mentions)
pub fn md_to_html(md: &str) -> (String, Vec<String>) {
let parser = Parser::new_ext(md, Options::all());
let (parser, mentions): (Vec<Vec<Event>>, Vec<Vec<String>>) = parser.map(|evt| match evt {
Event::Text(txt) => {
let (evts, _, _, _, new_mentions) = txt.chars().fold((vec![], false, String::new(), 0, vec![]), |(mut events, in_mention, text_acc, n, mut mentions), c| {
if in_mention {
if (c.is_alphanumeric() || c == '@' || c == '.' || c == '-' || c == '_') && (n < (txt.chars().count() - 1)) {
(events, in_mention, text_acc + c.to_string().as_ref(), n + 1, mentions)
} else {
let mention = text_acc + c.to_string().as_ref();
let short_mention = mention.clone();
let short_mention = short_mention.splitn(1, '@').nth(0).unwrap_or("");
let link = Tag::Link(format!("/@/{}/", mention).into(), short_mention.to_string().into());
mentions.push(mention);
events.push(Event::Start(link.clone()));
events.push(Event::Text(format!("@{}", short_mention).into()));
events.push(Event::End(link));
(events, false, c.to_string(), n + 1, mentions)
}
} else {
if c == '@' {
events.push(Event::Text(text_acc.into()));
(events, true, String::new(), n + 1, mentions)
} else {
if n >= (txt.chars().count() - 1) { // Add the text after at the end, even if it is not followed by a mention.
events.push(Event::Text((text_acc.clone() + c.to_string().as_ref()).into()))
}
(events, in_mention, text_acc + c.to_string().as_ref(), n + 1, mentions)
}
}
});
(evts, new_mentions)
},
_ => (vec![evt], vec![])
}).unzip();
let parser = parser.into_iter().flatten();
let mentions = mentions.into_iter().flatten().map(|m| String::from(m.trim()));
// TODO: fetch mentionned profiles in background, if needed
let mut buf = String::new();
html::push_html(&mut buf, parser);
(buf, mentions.collect())
}