This commit is contained in:
maurice committed 2026-11-14 17:25:55 +01:00
1 parent 377bd1e198
commit 139404b70f
17 files changed
+672 -48

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
use askama::Template;
use askama_web::WebTemplate;
use axum::{
extract::{Path, State},
http::{HeaderMap, StatusCode, header::ACCEPT},
response::{IntoResponse, Response},
};
use irosashi::{CodeToHtmlOptions, Highlighter};
use sqlx::SqlitePool;
use crate::paste::{Paste, PasteType};
#[derive(Template, WebTemplate)]
#[template(path = "note.html")]
pub struct NotePage {
code: String,
}
pub async fn get_note(
State(db): State<SqlitePool>,
Path(id): Path<String>,
headers: HeaderMap,
) -> Result<Response, StatusCode> {
let mut transaction = db
.begin()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let paste = sqlx::query_as::<_, Paste>(
"UPDATE notes SET views = views + 1
WHERE type = ? AND id = ?
AND (expiration IS NULL OR expiration > unixepoch())
AND (max_views IS NULL OR views < max_views)
RETURNING *",
)
.bind(PasteType::TextV1)
.bind(id)
.fetch_optional(&mut *transaction)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
if paste.max_views.is_some_and(|max| paste.views >= max) {
sqlx::query("DELETE FROM notes WHERE id = ?")
.bind(&paste.id)
.execute(&mut *transaction)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
transaction
.commit()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if return_html(headers) {
let highlighter = Highlighter::new().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let code = highlighter
.code_to_html(
&paste.content,
&CodeToHtmlOptions::new(
paste.language.as_deref().unwrap_or("text"),
"github-light",
),
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(NotePage { code }.into_response())
} else {
Ok(paste.content.into_response())
}
}
fn return_html(headers: HeaderMap) -> bool {
headers
.get(ACCEPT)
.and_then(|v| v.to_str().ok())
.map(|h| h.contains("text/html"))
.unwrap_or_default()
}