mirror of
https://codeberg.org/icewind/ptouch-api.git
synced 2026-06-03 10:54:07 +02:00
initial version
This commit is contained in:
parent
ddc5849ed6
commit
e37160b717
11 changed files with 2800 additions and 3 deletions
66
src/config.rs
Normal file
66
src/config.rs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
use serde::Deserialize;
|
||||
use std::fs::read_to_string;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::path::{Path, PathBuf};
|
||||
use thiserror::Error;
|
||||
use toml::from_str;
|
||||
|
||||
#[derive(Debug, Deserialize, Default)]
|
||||
pub struct Config {
|
||||
#[serde(default)]
|
||||
pub listen: ListenConfig,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn read<P: AsRef<Path>>(path: P) -> Result<Config, ConfigError> {
|
||||
let path = path.as_ref();
|
||||
let raw = read_to_string(path).map_err(|error| ConfigError::Read {
|
||||
error,
|
||||
path: path.to_owned(),
|
||||
})?;
|
||||
from_str(&raw).map_err(|error| ConfigError::Parse {
|
||||
error,
|
||||
path: path.to_owned(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum ListenConfig {
|
||||
Unix {
|
||||
socket: PathBuf,
|
||||
},
|
||||
Tcp {
|
||||
address: IpAddr,
|
||||
#[serde(default = "default_port")]
|
||||
port: u16,
|
||||
},
|
||||
}
|
||||
|
||||
impl Default for ListenConfig {
|
||||
fn default() -> Self {
|
||||
ListenConfig::Tcp {
|
||||
address: Ipv4Addr::new(127, 0, 0, 1).into(),
|
||||
port: default_port(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_port() -> u16 {
|
||||
7074
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("Error while reading config from {}: {error:#}", path.display())]
|
||||
Read {
|
||||
error: std::io::Error,
|
||||
path: PathBuf,
|
||||
},
|
||||
#[error("Error while parsing config from {}: {error:#}", path.display())]
|
||||
Parse {
|
||||
error: toml::de::Error,
|
||||
path: PathBuf,
|
||||
},
|
||||
}
|
||||
199
src/main.rs
199
src/main.rs
|
|
@ -1,3 +1,198 @@
|
|||
fn main() {
|
||||
println!("Hello, world!");
|
||||
mod config;
|
||||
|
||||
use crate::config::{Config, ListenConfig};
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, put};
|
||||
use axum::{Json, Router};
|
||||
use clap::Parser;
|
||||
use image::imageops::FilterType;
|
||||
use image::{EncodableLayout, ImageError, ImageReader};
|
||||
use listenfd::ListenFd;
|
||||
use main_error::MainResult;
|
||||
use ptouch_rs::{Printer, Status};
|
||||
use std::fs::{create_dir_all, remove_file, set_permissions};
|
||||
use std::io::Cursor;
|
||||
use std::net::SocketAddr;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use thiserror::Error;
|
||||
use tokio::net::UnixListener;
|
||||
use tokio::signal::ctrl_c;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{debug, info};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Args {
|
||||
/// Location of the config file
|
||||
#[clap(short, long)]
|
||||
config: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct App {
|
||||
printer: Arc<Mutex<Printer>>,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> MainResult {
|
||||
let args: Args = Args::parse();
|
||||
tracing_subscriber::fmt::init();
|
||||
let config = args
|
||||
.config
|
||||
.map(Config::read)
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut printer = Printer::open().await?;
|
||||
printer.reload_status().await?;
|
||||
|
||||
let state = App {
|
||||
printer: Arc::new(Mutex::new(printer)),
|
||||
};
|
||||
|
||||
let app = Router::new()
|
||||
.route("/status", get(status))
|
||||
.route("/print", put(print))
|
||||
.with_state(state.clone());
|
||||
|
||||
let cancel = async {
|
||||
ctrl_c().await.ok();
|
||||
};
|
||||
|
||||
let mut systemd_listener = ListenFd::from_env();
|
||||
|
||||
match (systemd_listener.take_unix_listener(0), &config.listen) {
|
||||
(Ok(Some(listener)), _) => {
|
||||
info!("listening on fd 0");
|
||||
let listener = UnixListener::from_std(listener).unwrap();
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(cancel)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
(_, ListenConfig::Unix { socket: path }) => {
|
||||
if let Some(parent) = path.parent() {
|
||||
if !parent.exists() {
|
||||
create_dir_all(parent).map_err(|error| SetupError::CreateSocketParent {
|
||||
error,
|
||||
path: parent.into(),
|
||||
})?;
|
||||
set_permissions(parent, PermissionsExt::from_mode(0o666)).map_err(|error| {
|
||||
SetupError::SocketParentPermissions {
|
||||
error,
|
||||
path: parent.into(),
|
||||
}
|
||||
})?;
|
||||
}
|
||||
}
|
||||
let _ = remove_file(path);
|
||||
|
||||
let uds = UnixListener::bind(path).map_err(|error| SetupError::BindUnix {
|
||||
error,
|
||||
path: path.clone(),
|
||||
})?;
|
||||
let _ = set_permissions(path, PermissionsExt::from_mode(0o666));
|
||||
|
||||
info!("listening on {}", path.display());
|
||||
|
||||
axum::serve(uds, app)
|
||||
.with_graceful_shutdown(cancel)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
(_, ListenConfig::Tcp { address, port }) => {
|
||||
let address = SocketAddr::new(*address, *port);
|
||||
let listener = tokio::net::TcpListener::bind(address)
|
||||
.await
|
||||
.map_err(|error| SetupError::BindTcp { error, address })?;
|
||||
info!("listening on {}", address);
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(cancel)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
enum SetupError {
|
||||
#[error("Error while creating parent folder ('{}') for unix socket: {error:#}", path.display())]
|
||||
CreateSocketParent {
|
||||
path: PathBuf,
|
||||
error: std::io::Error,
|
||||
},
|
||||
#[error("Error setting permissions on parent folder ('{}') for unix socket: {error:#}", path.display()
|
||||
)]
|
||||
SocketParentPermissions {
|
||||
path: PathBuf,
|
||||
error: std::io::Error,
|
||||
},
|
||||
#[error("Failed to bind unix socket {}: {error:#}", path.display())]
|
||||
BindUnix {
|
||||
path: PathBuf,
|
||||
error: std::io::Error,
|
||||
},
|
||||
#[error("Failed to bind tcp address {address}: {error:#}")]
|
||||
BindTcp {
|
||||
address: SocketAddr,
|
||||
error: std::io::Error,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
enum ApiError {
|
||||
#[error("Error communicating with printer: {0:#}")]
|
||||
Printer(#[from] ptouch_rs::Error),
|
||||
#[error("Error parsing image: {0:#}")]
|
||||
Image(#[from] ImageError),
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
pub fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
ApiError::Printer(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
ApiError::Image(_) => StatusCode::UNPROCESSABLE_ENTITY,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let status = self.status_code();
|
||||
let mut response = format!("{self:#}").into_response();
|
||||
*response.status_mut() = status;
|
||||
response
|
||||
}
|
||||
}
|
||||
|
||||
async fn status(State(state): State<App>) -> Result<Json<Status>, ApiError> {
|
||||
let mut printer = state.printer.lock().await;
|
||||
debug!("reloading printer status");
|
||||
printer.reload_status().await?;
|
||||
Ok(Json(printer.status()))
|
||||
}
|
||||
|
||||
async fn print(State(state): State<App>, bytes: Bytes) -> Result<(), ApiError> {
|
||||
let mut image = ImageReader::new(Cursor::new(bytes.as_bytes()))
|
||||
.with_guessed_format()
|
||||
.unwrap()
|
||||
.decode()?;
|
||||
let printer = state.printer.lock().await;
|
||||
let printer_info = printer.ty().info();
|
||||
|
||||
if image.height() != printer_info.max_px {
|
||||
let width = image.width() * printer_info.max_px / image.height();
|
||||
debug!(width, height = printer_info.max_px, "scaling image");
|
||||
image = image.resize(width, printer_info.max_px, FilterType::CatmullRom);
|
||||
}
|
||||
|
||||
info!(width = image.width(), height = image.height(), "printing");
|
||||
printer.print(image).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue