1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- 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<NaiveDateTime>,
- pub filetype: Option<String>,
- pub formatted_body: String,
- }
-
- #[derive(Insertable, AsChangeset, Serialize, Deserialize)]
- #[table_name = "snippets"]
- pub struct InsertableSnippet {
- pub title: String,
- pub body: String,
- pub filetype: Option<String>,
- pub formatted_body: String,
- }
-
- fn format_snippet(filetype: Option<String>, body: String) -> String {
- filetype.map_or(
- format!("<pre class='plaintext'>{}</pre>", body),
- |filetype| {
- let ps = SyntaxSet::load_defaults_newlines();
- let ts = ThemeSet::load_defaults();
- ps.find_syntax_by_extension(&filetype).map_or(
- format!("<pre class='plaintext'>{}</pre>", 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<Snippet> {
- snippets::table.find(id).get_result::<Snippet>(connection)
- }
-
- pub fn insert(snippet: InsertableSnippet, connection: &PGC) -> QueryResult<Snippet> {
- 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)
- }
|