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:
@@ -0,0 +1,64 @@
|
||||
[package]
|
||||
name = "plume-models"
|
||||
version = "0.1.0"
|
||||
authors = ["Baptiste Gelez <baptiste@gelez.xyz>"]
|
||||
|
||||
[dependencies]
|
||||
activitypub = "0.1.1"
|
||||
# activitystreams-derive = "0.1.0"
|
||||
# activitystreams-traits = "0.1.0"
|
||||
ammonia = "1.1.0"
|
||||
# array_tool = "1.0"
|
||||
# base64 = "0.9"
|
||||
bcrypt = "0.2"
|
||||
# colored = "1.6"
|
||||
# dotenv = "*"
|
||||
# failure = "0.1"
|
||||
# failure_derive = "0.1"
|
||||
# gettext-rs = "0.4"
|
||||
heck = "0.3.0"
|
||||
# hex = "0.3"
|
||||
# hyper = "*"
|
||||
lazy_static = "*"
|
||||
openssl = "0.10.6"
|
||||
reqwest = "0.8"
|
||||
# rpassword = "2.0"
|
||||
serde = "*"
|
||||
serde_derive = "1.0"
|
||||
serde_json = "1.0"
|
||||
# tera = "0.11"
|
||||
url = "1.7"
|
||||
webfinger = "0.1"
|
||||
#
|
||||
[dependencies.chrono]
|
||||
features = ["serde"]
|
||||
version = "0.4"
|
||||
|
||||
[dependencies.diesel]
|
||||
features = ["postgres", "r2d2", "chrono"]
|
||||
version = "*"
|
||||
|
||||
[dependencies.plume-common]
|
||||
path = "../plume-common"
|
||||
|
||||
# [dependencies.pulldown-cmark]
|
||||
# default-features = false
|
||||
# version = "0.1.2"
|
||||
#
|
||||
[dependencies.rocket]
|
||||
git = "https://github.com/SergioBenitez/Rocket"
|
||||
rev = "df7111143e466c18d1f56377a8d9530a5a306aba"
|
||||
#
|
||||
# [dependencies.rocket_codegen]
|
||||
# git = "https://github.com/SergioBenitez/Rocket"
|
||||
# rev = "df7111143e466c18d1f56377a8d9530a5a306aba"
|
||||
#
|
||||
# [dependencies.rocket_contrib]
|
||||
# features = ["tera_templates", "json"]
|
||||
# git = "https://github.com/SergioBenitez/Rocket"
|
||||
# rev = "df7111143e466c18d1f56377a8d9530a5a306aba"
|
||||
#
|
||||
# [dependencies.rocket_i18n]
|
||||
# git = "https://github.com/BaptisteGelez/rocket_i18n"
|
||||
# rev = "5b4225d5bed5769482dc926a7e6d6b79f1217be6"
|
||||
#
|
||||
@@ -0,0 +1,24 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
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 plume_common::activity_pub::{
|
||||
ApSignature, ActivityStream, Id, IntoId, PublicKey,
|
||||
inbox::WithInbox,
|
||||
sign
|
||||
};
|
||||
use 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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
use activitypub::{
|
||||
activity::Create,
|
||||
link,
|
||||
object::{Note}
|
||||
};
|
||||
use chrono;
|
||||
use diesel::{self, PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods, dsl::any};
|
||||
use serde_json;
|
||||
|
||||
use plume_common::activity_pub::{
|
||||
ap_url, Id, IntoId, PUBLIC_VISIBILTY,
|
||||
inbox::{FromActivity, Notify}
|
||||
};
|
||||
use plume_common::utils;
|
||||
use get_next_id;
|
||||
use instance::Instance;
|
||||
use mentions::Mention;
|
||||
use notifications::*;
|
||||
use posts::Post;
|
||||
use users::User;
|
||||
use schema::comments;
|
||||
use safe_string::SafeString;
|
||||
|
||||
#[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, PgConnection> 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(¬e.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<PgConnection> 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use diesel::{
|
||||
pg::PgConnection,
|
||||
r2d2::{ConnectionManager, Pool, PooledConnection}
|
||||
};
|
||||
use rocket::{Request, State, Outcome, http::Status, request::{self, FromRequest}};
|
||||
use std::ops::Deref;
|
||||
|
||||
pub type PgPool = Pool<ConnectionManager<PgConnection>>;
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use activitypub::{Actor, activity::{Accept, Follow as FollowAct}};
|
||||
use diesel::{self, PgConnection, ExpressionMethods, QueryDsl, RunQueryDsl};
|
||||
|
||||
use plume_common::activity_pub::{broadcast, Id, IntoId, inbox::{FromActivity, Notify, WithInbox}, sign::Signer};
|
||||
use blogs::Blog;
|
||||
use notifications::*;
|
||||
use 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, PgConnection> 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<PgConnection> 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
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use chrono::NaiveDateTime;
|
||||
use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods, PgConnection};
|
||||
use std::iter::Iterator;
|
||||
|
||||
use plume_common::activity_pub::ap_url;
|
||||
use 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
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
extern crate activitypub;
|
||||
extern crate ammonia;
|
||||
extern crate bcrypt;
|
||||
extern crate chrono;
|
||||
#[macro_use]
|
||||
extern crate diesel;
|
||||
extern crate heck;
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
extern crate openssl;
|
||||
extern crate plume_common;
|
||||
extern crate reqwest;
|
||||
extern crate rocket;
|
||||
extern crate serde;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
#[macro_use]
|
||||
extern crate serde_json;
|
||||
extern crate url;
|
||||
extern crate webfinger;
|
||||
|
||||
use diesel::{PgConnection, RunQueryDsl, select};
|
||||
use std::env;
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
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"))));
|
||||
}
|
||||
|
||||
pub mod blog_authors;
|
||||
pub mod blogs;
|
||||
pub mod comments;
|
||||
pub mod db_conn;
|
||||
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 safe_string;
|
||||
pub mod schema;
|
||||
pub mod users;
|
||||
@@ -0,0 +1,116 @@
|
||||
use activitypub::activity;
|
||||
use chrono;
|
||||
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
|
||||
|
||||
use plume_common::activity_pub::{
|
||||
PUBLIC_VISIBILTY,
|
||||
Id,
|
||||
IntoId,
|
||||
inbox::{FromActivity, Deletable, Notify}
|
||||
};
|
||||
use notifications::*;
|
||||
use posts::Post;
|
||||
use 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, PgConnection> 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<PgConnection> 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<PgConnection> 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
use activitypub::link;
|
||||
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
|
||||
|
||||
use plume_common::activity_pub::inbox::Notify;
|
||||
use comments::Comment;
|
||||
use notifications::*;
|
||||
use posts::Post;
|
||||
use 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<PgConnection> 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
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use chrono::NaiveDateTime;
|
||||
use diesel::{self, PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods};
|
||||
|
||||
use 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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
|
||||
|
||||
use posts::Post;
|
||||
use 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);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
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 plume_common::activity_pub::{
|
||||
PUBLIC_VISIBILTY, ap_url, Id, IntoId,
|
||||
inbox::FromActivity
|
||||
};
|
||||
use blogs::Blog;
|
||||
use instance::Instance;
|
||||
use likes::Like;
|
||||
use mentions::Mention;
|
||||
use post_authors::*;
|
||||
use reshares::Reshare;
|
||||
use 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, PgConnection> 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())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use activitypub::activity::{Announce, Undo};
|
||||
use chrono::NaiveDateTime;
|
||||
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
|
||||
|
||||
use plume_common::activity_pub::{Id, IntoId, inbox::{FromActivity, Notify, Deletable}, PUBLIC_VISIBILTY};
|
||||
use notifications::*;
|
||||
use posts::Post;
|
||||
use 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, PgConnection> 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<PgConnection> 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<PgConnection> 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
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,
|
||||
);
|
||||
@@ -0,0 +1,460 @@
|
||||
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 plume_common::activity_pub::{
|
||||
ap_url, ActivityStream, Id, IntoId, ApSignature, PublicKey,
|
||||
inbox::WithInbox,
|
||||
sign::{Signer, gen_keypair}
|
||||
};
|
||||
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 db_conn::DbConn;
|
||||
use blogs::Blog;
|
||||
use blog_authors::BlogAuthor;
|
||||
use follows::Follow;
|
||||
use instance::*;
|
||||
use likes::Like;
|
||||
use post_authors::PostAuthor;
|
||||
use posts::Post;
|
||||
use reshares::Reshare;
|
||||
use safe_string::SafeString;
|
||||
use schema::users;
|
||||
|
||||
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;
|
||||
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;
|
||||
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 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
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user