lib.rs
⎇
Raw
1//! filebrowser-ng server.
2//!
3//! Library target so the HTTP app can be exercised from integration tests
4//! (via `tower::ServiceExt::oneshot`) without binding a real port. The
5//! `filebrowser-ng` binary is a thin wrapper around [`run`].
6
7use std::net::{IpAddr, SocketAddr};
8use std::sync::Arc;
9
10use anyhow::{Context, bail};
11use clap::Parser;
12use tower_http::trace::TraceLayer;
13
14pub mod api;
15pub mod archive;
16mod assets;
17pub mod auth;
18pub mod cli;
19pub mod db;
20pub mod error;
21pub mod fs;
22
23use crate::cli::Cli;
24use crate::db::Db;
25use crate::error::AppState;
26
27/// Validate the CLI config and build the running state + router without
28/// binding the port (so tests can exercise everything up to `serve`).
29pub async fn build_app(cli: &Cli) -> anyhow::Result<(axum::Router, SocketAddr)> {
30 let root = cli
31 .root
32 .canonicalize()
33 .with_context(|| format!("cannot resolve root folder: {}", cli.root.display()))?;
34 if !root.is_dir() {
35 bail!("root folder is not a directory: {}", root.display());
36 }
37
38 let db = Db::open(&cli.db).await?;
39
40 let root_name = cli
41 .root_name
42 .clone()
43 .filter(|n| !n.trim().is_empty())
44 .unwrap_or_else(|| root_file_name(&root));
45 let state = Arc::new(AppState {
46 db,
47 root: root.clone(),
48 root_name,
49 https: cli.https,
50 });
51
52 let app = api::router(state).layer(TraceLayer::new_for_http());
53
54 let ip: IpAddr = cli.bind.parse().context("invalid --bind address")?;
55 let addr = SocketAddr::new(ip, cli.port);
56 Ok((app, addr))
57}
58
59/// Parse the CLI, initialize logging and serve until the process is killed.
60pub async fn run() -> anyhow::Result<()> {
61 tracing_subscriber::fmt()
62 .with_env_filter(
63 tracing_subscriber::EnvFilter::try_from_default_env()
64 .unwrap_or_else(|_| "info,tower_http=warn".into()),
65 )
66 .init();
67
68 let cli = Cli::parse();
69 let (app, addr) = build_app(&cli).await?;
70 let listener = tokio::net::TcpListener::bind(addr)
71 .await
72 .with_context(|| format!("cannot bind to {addr}"))?;
73
74 tracing::info!(root = %cli.root.display(), "filebrowser-ng starting");
75 tracing::info!(addr = %addr, "listening (pass --bind 0.0.0.0 to expose beyond localhost)");
76 axum::serve(listener, app).await?;
77 Ok(())
78}
79
80/// The root folder's own name; "/" has none, so fall back to the full path.
81pub fn root_file_name(root: &std::path::Path) -> String {
82 root.file_name()
83 .map(|s| s.to_string_lossy().into_owned())
84 .unwrap_or_else(|| root.display().to_string())
85}
86
87#[cfg(test)]
88mod tests {
89 use super::*;
90 use crate::cli::Cli;
91
92 fn cli(root: &std::path::Path, db: &std::path::Path) -> Cli {
93 Cli {
94 root: root.to_path_buf(),
95 db: db.to_path_buf(),
96 root_name: None,
97 port: 8080,
98 bind: "127.0.0.1".into(),
99 https: false,
100 }
101 }
102
103 #[tokio::test]
104 async fn build_app_ok() {
105 let tmp = tempfile::tempdir().unwrap();
106 std::fs::create_dir_all(tmp.path().join("sub")).unwrap();
107 let c = cli(tmp.path(), &tmp.path().join("db.sqlite"));
108 let (app, addr) = build_app(&c).await.unwrap();
109 let _ = app; // Router built fine
110 assert_eq!(addr.to_string(), "127.0.0.1:8080");
111 }
112
113 #[tokio::test]
114 async fn build_app_missing_root_fails() {
115 let tmp = tempfile::tempdir().unwrap();
116 let c = cli(
117 &tmp.path().join("no-such-root"),
118 &tmp.path().join("db.sqlite"),
119 );
120 assert!(build_app(&c).await.is_err());
121 }
122
123 #[tokio::test]
124 async fn build_app_root_must_be_directory() {
125 let tmp = tempfile::tempdir().unwrap();
126 let file = tmp.path().join("a-file");
127 std::fs::write(&file, "x").unwrap();
128 let c = cli(&file, &tmp.path().join("db.sqlite"));
129 assert!(build_app(&c).await.is_err());
130 }
131
132 #[tokio::test]
133 async fn build_app_rejects_bad_bind() {
134 let tmp = tempfile::tempdir().unwrap();
135 let mut c = cli(tmp.path(), &tmp.path().join("db.sqlite"));
136 c.bind = "not-an-ip".into();
137 assert!(build_app(&c).await.is_err());
138 }
139
140 #[tokio::test]
141 async fn build_app_custom_port_bind() {
142 let tmp = tempfile::tempdir().unwrap();
143 let mut c = cli(tmp.path(), &tmp.path().join("db.sqlite"));
144 c.port = 9999;
145 c.bind = "0.0.0.0".into();
146 let (_app, addr) = build_app(&c).await.unwrap();
147 assert_eq!(addr.to_string(), "0.0.0.0:9999");
148 }
149}
150