use chrono::NaiveDateTime; use diesel::pg::PgConnection as PGC; use diesel::prelude::*; use syntect::highlighting::ThemeSet; use syntect::html::highlighted_html_for_string; use syntect::parsing::SyntaxSet; use crate::schema::snippets; #[derive(Queryable, Serialize, Deserialize)] pub struct Snippet { pub id: i32, pub title: String, pub body: String, pub created_at: Option, pub filetype: Option, pub formatted_body: String, } #[derive(Insertable, AsChangeset, Serialize, Deserialize)] #[table_name = "snippets"] pub struct InsertableSnippet { pub title: String, pub body: String, pub filetype: Option, pub formatted_body: String, } fn format_snippet(filetype: Option, body: String) -> String { filetype.map_or( format!("
\n{}\n
", body), |filetype| { let ps = SyntaxSet::load_defaults_newlines(); let ts = ThemeSet::load_defaults(); ps.find_syntax_by_extension(&filetype).map_or( format!("
\n{}\n
", body), |syntax| { highlighted_html_for_string( &htmlescape::decode_html(&body).expect("Invalid HTML"), &ps, syntax, &ts.themes["Solarized (light)"], ) }, ) }, ) } pub fn get(connection: &PGC, id: i32) -> QueryResult { snippets::table.find(id).get_result::(connection) } pub fn insert(snippet: InsertableSnippet, connection: &PGC) -> QueryResult { let body = htmlescape::encode_minimal(&snippet.body.clone()); let formatted_snippet = InsertableSnippet { filetype: snippet.filetype.clone(), title: snippet.title, body: body.clone(), formatted_body: format_snippet(snippet.filetype, body), }; diesel::insert_into(snippets::table) .values(formatted_snippet) .get_result(connection) }