Plume/src/models/posts.rs

86 lines
2.5 KiB
Rust
Raw Normal View History

2018-04-30 19:46:27 +02:00
use chrono::NaiveDateTime;
2018-04-30 18:50:35 +02:00
use diesel::{self, PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods, BelongingToDsl};
use diesel::dsl::any;
2018-04-29 22:23:44 +02:00
use serde_json;
2018-04-24 11:21:39 +02:00
2018-04-30 18:50:35 +02:00
use activity_pub::PUBLIC_VISIBILTY;
use activity_pub::actor::Actor;
2018-04-29 22:23:44 +02:00
use activity_pub::object::Object;
2018-04-30 18:50:35 +02:00
use models::users::User;
use models::post_authors::PostAuthor;
2018-04-23 15:41:43 +02:00
use schema::posts;
#[derive(Queryable, Identifiable)]
pub struct Post {
pub id: i32,
pub blog_id: i32,
pub slug: String,
pub title: String,
pub content: String,
pub published: bool,
2018-04-30 19:46:27 +02:00
pub license: String,
pub creation_date: NaiveDateTime
2018-04-23 15:41:43 +02:00
}
#[derive(Insertable)]
#[table_name = "posts"]
pub struct NewPost {
pub blog_id: i32,
pub slug: String,
pub title: String,
pub content: String,
pub published: bool,
pub license: String
}
impl Post {
pub fn insert (conn: &PgConnection, new: NewPost) -> Post {
diesel::insert_into(posts::table)
.values(new)
.get_result(conn)
.expect("Error saving new post")
}
pub fn get(conn: &PgConnection, id: i32) -> Option<Post> {
posts::table.filter(posts::id.eq(id))
.limit(1)
.load::<Post>(conn)
.expect("Error loading post by id")
.into_iter().nth(0)
}
2018-04-23 16:25:39 +02:00
pub fn find_by_slug(conn: &PgConnection, slug: String) -> Option<Post> {
posts::table.filter(posts::slug.eq(slug))
.limit(1)
.load::<Post>(conn)
.expect("Error loading post by slug")
.into_iter().nth(0)
}
2018-04-30 18:50:35 +02:00
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()
}
2018-04-23 15:41:43 +02:00
}
2018-04-29 22:23:44 +02:00
impl Object for Post {
2018-04-30 18:50:35 +02:00
fn serialize(&self, conn: &PgConnection) -> serde_json::Value {
json!({
"type": "Article",
"attributedTo": self.get_authors(conn).into_iter().map(|a| a.compute_id(conn)).collect::<Vec<String>>(),
"content": self.content,
// TODO: "image": "image",
// TODO: "preview": "preview",
// TODO: "published": "published",
// TODO: "replies": "replies",
// TODO: "summary": "summary",
"tag": [],
// TODO: "updated": "updated",
// TODO: "url": "url",
"to": [ PUBLIC_VISIBILTY ]
})
2018-04-29 22:23:44 +02:00
}
}