2018-05-10 17:54:35 +02:00
|
|
|
use chrono;
|
2018-05-10 18:07:23 +02:00
|
|
|
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
|
2018-05-12 23:34:13 +02:00
|
|
|
use serde_json;
|
2018-05-10 17:54:35 +02:00
|
|
|
|
2018-05-12 23:34:13 +02:00
|
|
|
use activity_pub::actor::Actor;
|
|
|
|
use activity_pub::object::Object;
|
2018-05-12 22:56:57 +02:00
|
|
|
use models::posts::Post;
|
|
|
|
use models::users::User;
|
2018-05-10 17:54:35 +02:00
|
|
|
use schema::likes;
|
|
|
|
|
2018-05-12 22:56:57 +02:00
|
|
|
#[derive(Queryable, Identifiable)]
|
2018-05-10 17:54:35 +02:00
|
|
|
pub struct Like {
|
2018-05-10 18:07:23 +02:00
|
|
|
pub id: i32,
|
|
|
|
pub user_id: i32,
|
|
|
|
pub post_id: i32,
|
|
|
|
pub creation_date: chrono::NaiveDateTime
|
2018-05-10 17:54:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Insertable)]
|
|
|
|
#[table_name = "likes"]
|
|
|
|
pub struct NewLike {
|
2018-05-10 18:07:23 +02:00
|
|
|
pub user_id: i32,
|
|
|
|
pub post_id: i32
|
2018-05-10 17:54:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Like {
|
2018-05-10 18:07:23 +02:00
|
|
|
pub fn insert(conn: &PgConnection, new: NewLike) -> Like {
|
|
|
|
diesel::insert_into(likes::table)
|
|
|
|
.values(new)
|
|
|
|
.get_result(conn)
|
|
|
|
.expect("Unable to insert new like")
|
|
|
|
}
|
|
|
|
|
2018-05-10 17:54:35 +02:00
|
|
|
pub fn get(conn: &PgConnection, id: i32) -> Option<Like> {
|
|
|
|
likes::table.filter(likes::id.eq(id))
|
|
|
|
.limit(1)
|
|
|
|
.load::<Like>(conn)
|
|
|
|
.expect("Error loading like by ID")
|
|
|
|
.into_iter().nth(0)
|
|
|
|
}
|
2018-05-12 22:56:57 +02:00
|
|
|
|
|
|
|
pub fn for_user_on_post(conn: &PgConnection, user: &User, post: &Post) -> Option<Like> {
|
|
|
|
likes::table.filter(likes::post_id.eq(post.id))
|
|
|
|
.filter(likes::user_id.eq(user.id))
|
|
|
|
.limit(1)
|
|
|
|
.load::<Like>(conn)
|
|
|
|
.expect("Error loading like for user and post")
|
|
|
|
.into_iter().nth(0)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn delete(&self, conn: &PgConnection) {
|
|
|
|
diesel::delete(self).execute(conn).unwrap();
|
|
|
|
}
|
2018-05-10 17:54:35 +02:00
|
|
|
}
|
2018-05-12 23:34:13 +02:00
|
|
|
|
|
|
|
impl Object for Like {
|
|
|
|
fn serialize(&self, conn: &PgConnection) -> serde_json::Value {
|
|
|
|
json!({
|
|
|
|
"id": self.compute_id(conn)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
fn compute_id(&self, conn: &PgConnection) -> String {
|
|
|
|
format!(
|
|
|
|
"{}/like/{}",
|
|
|
|
User::get(conn, self.user_id).unwrap().compute_id(conn),
|
|
|
|
Post::get(conn, self.post_id).unwrap().compute_id(conn)
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|