1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- use chrono::NaiveDateTime;
- use crypto::digest::Digest;
- use crypto::sha2::Sha256;
- 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;
- use crate::schema::snippets::columns::uuid;
-
- #[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,
- pub uuid: String,
- }
-
- #[derive(Serialize, Deserialize)]
- pub struct ApiSnippet {
- pub title: String,
- pub body: String,
- pub filetype: Option<String>,
- }
-
- #[derive(Insertable, AsChangeset)]
- #[table_name = "snippets"]
- pub struct InsertableSnippet {
- pub title: String,
- pub body: String,
- pub filetype: Option<String>,
- pub formatted_body: String,
- pub uuid: String,
- }
-
- fn format_snippet(filetype: Option<String>, body: String) -> String {
- filetype.map_or(
- format!("<pre class='plaintext'>\n{}\n</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'>\n{}\n</pre>", body),
- |syntax| {
- highlighted_html_for_string(
- &htmlescape::decode_html(&body).expect("Invalid HTML"),
- &ps,
- syntax,
- &ts.themes["Solarized (light)"],
- )
- },
- )
- },
- )
- }
-
- fn generate_uuid(snippet: &ApiSnippet) -> String {
- let mut hasher = Sha256::new();
- hasher.input_str(&format!("{}{}", snippet.title, snippet.body));
- hasher.result_str().to_string()
- }
-
- pub fn get(connection: &PGC, snippet_uuid: &str) -> QueryResult<Snippet> {
- snippets::table
- .filter(uuid.eq(snippet_uuid))
- .first(connection)
- }
-
- pub fn insert(snippet: ApiSnippet, connection: &PGC) -> QueryResult<Snippet> {
- let body = htmlescape::encode_minimal(&snippet.body.clone());
- let formatted_snippet = InsertableSnippet {
- filetype: snippet.filetype.clone(),
- title: snippet.title.clone(),
- body: body.clone(),
- uuid: generate_uuid(&snippet),
- formatted_body: format_snippet(snippet.filetype, body),
- };
- diesel::insert_into(snippets::table)
- .values(formatted_snippet)
- .get_result(connection)
- }
|