Plume/plume-models/src/medias.rs

75 lines
2.7 KiB
Rust
Raw Normal View History

2018-09-02 13:34:48 +02:00
use diesel::{self, PgConnection, QueryDsl, ExpressionMethods, RunQueryDsl};
2018-09-02 22:55:42 +02:00
use serde_json;
2018-09-02 23:10:15 +02:00
use std::fs;
2018-09-02 22:55:42 +02:00
use ap_url;
use instance::Instance;
2018-09-02 13:34:48 +02:00
use schema::medias;
2018-09-02 23:10:15 +02:00
#[derive(Identifiable, Queryable, Serialize)]
2018-09-02 13:34:48 +02:00
pub struct Media {
pub id: i32,
pub file_path: String,
pub alt_text: String,
pub is_remote: bool,
pub remote_url: Option<String>,
pub sensitive: bool,
2018-09-02 22:55:42 +02:00
pub content_warning: Option<String>,
pub owner_id: i32
2018-09-02 13:34:48 +02:00
}
#[derive(Insertable)]
#[table_name = "medias"]
pub struct NewMedia {
pub file_path: String,
pub alt_text: String,
pub is_remote: bool,
pub remote_url: Option<String>,
pub sensitive: bool,
2018-09-02 22:55:42 +02:00
pub content_warning: Option<String>,
pub owner_id: i32
2018-09-02 13:34:48 +02:00
}
impl Media {
insert!(medias, NewMedia);
get!(medias);
2018-09-02 22:55:42 +02:00
list_by!(medias, for_user, owner_id as i32);
pub fn to_json(&self, conn: &PgConnection) -> serde_json::Value {
let mut json = serde_json::to_value(self).unwrap();
let url = self.url(conn);
let (preview, html, md) = match self.file_path.rsplitn(2, '.').next().unwrap() {
2018-09-03 11:22:14 +02:00
"png" | "jpg" | "jpeg" | "gif" | "svg" => (
format!("<img src=\"{}\" alt=\"{}\" title=\"{}\" class=\"preview\">", url, self.alt_text, self.alt_text),
format!("<img src=\"{}\" alt=\"{}\" title=\"{}\">", url, self.alt_text, self.alt_text),
format!("![{}]({})", self.alt_text, url),
2018-09-02 22:55:42 +02:00
),
"mp3" | "wav" | "flac" => (
format!("<audio src=\"{}\" title=\"{}\" class=\"preview\"></audio>", url, self.alt_text),
format!("<audio src=\"{}\" title=\"{}\"></audio>", url, self.alt_text),
format!("<audio src=\"{}\" title=\"{}\"></audio>", url, self.alt_text),
2018-09-02 22:55:42 +02:00
),
"mp4" | "avi" | "webm" | "mov" => (
format!("<video src=\"{}\" title=\"{}\" class=\"preview\"></video>", url, self.alt_text),
format!("<video src=\"{}\" title=\"{}\"></video>", url, self.alt_text),
format!("<video src=\"{}\" title=\"{}\"></video>", url, self.alt_text),
2018-09-02 22:55:42 +02:00
),
_ => (String::new(), String::new(), String::new())
2018-09-02 22:55:42 +02:00
};
json["html_preview"] = json!(preview);
json["html"] = json!(html);
json["url"] = json!(url);
json["md"] = json!(md);
2018-09-02 22:55:42 +02:00
json
}
pub fn url(&self, conn: &PgConnection) -> String {
ap_url(format!("{}/static/{}", Instance::get_local(conn).unwrap().public_domain, self.file_path))
}
2018-09-02 23:10:15 +02:00
pub fn delete(&self, conn: &PgConnection) {
fs::remove_file(self.file_path.as_str()).expect("Couldn't delete media from disk");
diesel::delete(self).execute(conn).expect("Couldn't remove media from DB");
}
2018-09-02 13:34:48 +02:00
}