lib.rs
⎇
Raw
1//! The HTTP wire contract of filebrowser-ng in one place.
2//!
3//! Both the server (axum) and the web frontend (wasm `fetch`) import these
4//! endpoint paths, query params and serde types, so the two sides cannot
5//! drift apart. Serde only — no axum, no wasm dependencies.
6
7use serde::{Deserialize, Serialize};
8
9// ---------------------------------------------------------------------------
10// Endpoint paths (single source of truth for the route table and the client)
11// ---------------------------------------------------------------------------
12
13pub const AUTH_LOGIN: &str = "/api/auth/login";
14pub const AUTH_LOGOUT: &str = "/api/auth/logout";
15pub const AUTH_ME: &str = "/api/auth/me";
16pub const AUTH_SETUP: &str = "/api/auth/setup";
17/// File operations: `{FILES}/{root_id}` and `{FILES}/{root_id}/{path...}`.
18pub const FILES: &str = "/api/files";
19/// Share management (authenticated): `{SHARES}` and `{SHARES}/{id}`.
20pub const SHARES: &str = "/api/shares";
21/// Public share resolve (no login): `{SHARE}/{token}`.
22pub const SHARE: &str = "/api/share";
23/// Admin user management: `{ADMIN_USERS}` and `{ADMIN_USERS}/{id}`.
24pub const ADMIN_USERS: &str = "/api/admin/users";
25pub const ADMIN_SETTINGS: &str = "/api/admin/settings";
26
27// ---------------------------------------------------------------------------
28// Query params
29// ---------------------------------------------------------------------------
30
31/// `?action=...` on file URLs; without it the route lists the directory.
32pub const P_ACTION: &str = "action";
33pub const ACTION_DOWNLOAD: &str = "download";
34pub const ACTION_PREVIEW: &str = "preview";
35pub const ACTION_CONTENT: &str = "content";
36/// `POST {FILES}/...?action=mkdir` — create a folder. Explicit, because the
37/// POST route also carries uploads and mutations.
38pub const ACTION_MKDIR: &str = "mkdir";
39/// `?format=...` for folder downloads (values: see `server::archive::ArchiveFormat`).
40pub const P_FORMAT: &str = "format";
41/// `?share=<token>` — authenticate file calls with a public share token.
42pub const P_SHARE: &str = "share";
43/// `?overwrite=true|1` on mutations and uploads.
44pub const P_OVERWRITE: &str = "overwrite";
45
46// ---------------------------------------------------------------------------
47// Wire enums
48// ---------------------------------------------------------------------------
49
50/// Access mode of a root or a share.
51///
52/// The serde names are also the values stored in the SQLite `mode` columns,
53/// so renaming a variant would break existing databases. The round-trip test
54/// below pins them.
55#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
56#[serde(rename_all = "lowercase")]
57pub enum Mode {
58 Rw,
59 Ro,
60}
61
62impl Mode {
63 /// The only question callers ask: may this root be written to?
64 pub fn is_writable(self) -> bool {
65 matches!(self, Mode::Rw)
66 }
67
68 /// The wire/database spelling, for `<select>` values and SQL params.
69 pub fn as_str(self) -> &'static str {
70 match self {
71 Mode::Rw => "rw",
72 Mode::Ro => "ro",
73 }
74 }
75
76 /// Parse the wire spelling. `None` for anything else.
77 pub fn from_wire(s: &str) -> Option<Self> {
78 match s {
79 "rw" => Some(Mode::Rw),
80 "ro" => Some(Mode::Ro),
81 _ => None,
82 }
83 }
84}
85
86/// Which mutation [`Mutation`] asks for.
87#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
88#[serde(rename_all = "lowercase")]
89pub enum Op {
90 Rename,
91 Move,
92 Copy,
93}
94
95// ---------------------------------------------------------------------------
96// Request bodies (client → server)
97// ---------------------------------------------------------------------------
98
99#[derive(Serialize, Deserialize)]
100pub struct Credentials {
101 pub name: String,
102 pub password: String,
103}
104
105/// Rename / move / copy (one body for all file mutations).
106#[derive(Serialize, Deserialize)]
107pub struct Mutation {
108 pub op: Op,
109 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub new_name: Option<String>,
111 #[serde(default, skip_serializing_if = "Option::is_none")]
112 pub dst_root_id: Option<i64>,
113 /// Destination directory, relative to `dst_root_id`.
114 #[serde(default, skip_serializing_if = "Option::is_none")]
115 pub dst: Option<String>,
116 #[serde(default)]
117 pub overwrite: bool,
118}
119
120/// A user folder: path relative to the server root + access mode.
121#[derive(Serialize, Deserialize)]
122pub struct Root {
123 /// Path relative to the server root; "." means the whole root.
124 pub path: String,
125 #[serde(default = "default_rw")]
126 pub mode: Mode,
127}
128
129fn default_rw() -> Mode {
130 Mode::Rw
131}
132
133#[derive(Serialize, Deserialize)]
134pub struct CreateUser {
135 pub name: String,
136 pub password: String,
137 #[serde(default)]
138 pub is_admin: bool,
139 #[serde(default)]
140 pub roots: Vec<Root>,
141}
142
143#[derive(Serialize, Deserialize)]
144pub struct UpdateUser {
145 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub password: Option<String>,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub is_admin: Option<bool>,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub active: Option<bool>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub roots: Option<Vec<Root>>,
153}
154
155/// Server settings (GET/PUT `{ADMIN_SETTINGS}`).
156#[derive(Serialize, Deserialize, Clone, Copy)]
157pub struct Settings {
158 pub allow_writable_shares: bool,
159}
160
161#[derive(Serialize, Deserialize)]
162pub struct CreateShare {
163 pub root_id: i64,
164 /// Item path relative to the root ("" or "." for the root itself).
165 pub path: String,
166 #[serde(default)]
167 pub writable: bool,
168 /// Absolute expiry as RFC 3339; absent = never.
169 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub expires_at: Option<String>,
171}
172
173// ---------------------------------------------------------------------------
174// Responses (server → client)
175// ---------------------------------------------------------------------------
176
177/// What a listing entry actually is, decided by the server from the file's
178/// leading bytes (magic numbers via `infer`, plus a text/binary heuristic) —
179/// not from its name. Drives the icon and the preview the client offers.
180///
181/// Deliberately coarse: this answers "which viewer opens this", not "what
182/// exact format is it". Syntax highlighting still keys off the extension,
183/// because `.h` is C or C++ and no amount of sniffing decides that.
184#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
185#[serde(rename_all = "lowercase")]
186pub enum FileKind {
187 Dir,
188 Image,
189 Video,
190 Audio,
191 Pdf,
192 Archive,
193 /// Anything that decodes as text: source code, markup, config, plain text.
194 Text,
195 /// Recognized-but-not-viewable, or undecodable bytes.
196 Binary,
197}
198
199#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
200pub struct Entry {
201 pub name: String,
202 pub is_dir: bool,
203 pub size: u64,
204 /// RFC 3339 UTC modification time.
205 pub mtime: String,
206 /// Content-sniffed kind (see [`FileKind`]).
207 pub kind: FileKind,
208}
209
210#[derive(Serialize, Deserialize)]
211pub struct FilesResp {
212 pub entries: Vec<Entry>,
213}
214
215#[derive(Serialize, Deserialize, Clone)]
216pub struct UserInfo {
217 pub id: i64,
218 pub name: String,
219 pub is_admin: bool,
220}
221
222#[derive(Serialize, Deserialize, Clone)]
223pub struct RootInfo {
224 pub id: i64,
225 pub name: String,
226 pub path: String,
227 pub mode: Mode,
228}
229
230/// GET `{AUTH_ME}`.
231#[derive(Serialize, Deserialize, Clone)]
232pub struct Me {
233 /// True while no users exist yet (first-boot setup).
234 pub first_boot: bool,
235 /// None on first boot.
236 pub user: Option<UserInfo>,
237 pub roots: Vec<RootInfo>,
238 pub allow_writable_shares: bool,
239}
240
241/// GET/POST `{SHARES}`, GET `{SHARE}/{token}`.
242#[derive(Serialize, Deserialize, Clone)]
243pub struct ShareInfo {
244 pub id: i64,
245 pub token: String,
246 /// Display name (file/folder name, or the root's name for ".").
247 pub name: String,
248 pub is_file: bool,
249 pub writable: bool,
250 /// Path relative to the server root.
251 pub target: String,
252 /// RFC 3339 UTC creation time.
253 pub created_at: String,
254 /// RFC 3339 UTC expiry; None = never.
255 pub expires_at: Option<String>,
256 /// Synthetic root id to use in file API calls.
257 pub root_id: i64,
258}
259
260/// GET/POST `{ADMIN_USERS}`, PUT `{ADMIN_USERS}/{id}`.
261#[derive(Serialize, Deserialize, Clone)]
262pub struct AdminUser {
263 pub id: i64,
264 pub name: String,
265 pub is_admin: bool,
266 pub active: bool,
267 pub roots: Vec<RootInfo>,
268}
269
270/// Acknowledges a successful mutation: `{"ok": true}`.
271#[derive(Serialize, Deserialize)]
272pub struct OkResp {
273 pub ok: bool,
274}
275
276/// Upload success: `{"ok": true, "uploaded": n}`.
277#[derive(Serialize, Deserialize)]
278pub struct UploadResp {
279 pub ok: bool,
280 pub uploaded: usize,
281}
282
283/// PUT `?action=content` (editor save): the file's new mtime (unix seconds).
284#[derive(Serialize, Deserialize)]
285pub struct SaveResp {
286 pub ok: bool,
287 pub mtime: i64,
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293
294 /// The serde spellings are the database values too, so they are pinned.
295 #[test]
296 fn mode_wire_format_is_rw_ro() {
297 assert_eq!(serde_json::to_string(&Mode::Rw).unwrap(), "\"rw\"");
298 assert_eq!(serde_json::to_string(&Mode::Ro).unwrap(), "\"ro\"");
299 for m in [Mode::Rw, Mode::Ro] {
300 let s = serde_json::to_string(&m).unwrap();
301 assert_eq!(serde_json::from_str::<Mode>(&s).unwrap(), m);
302 // `as_str`/`from_wire` must agree with serde.
303 assert_eq!(s, format!("\"{}\"", m.as_str()));
304 assert_eq!(Mode::from_wire(m.as_str()), Some(m));
305 }
306 assert_eq!(Mode::from_wire("both"), None);
307 assert!(serde_json::from_str::<Mode>("\"both\"").is_err());
308 assert!(Mode::Rw.is_writable());
309 assert!(!Mode::Ro.is_writable());
310 }
311
312 #[test]
313 fn op_wire_format() {
314 assert_eq!(serde_json::to_string(&Op::Rename).unwrap(), "\"rename\"");
315 assert_eq!(serde_json::to_string(&Op::Move).unwrap(), "\"move\"");
316 assert_eq!(serde_json::to_string(&Op::Copy).unwrap(), "\"copy\"");
317 for op in [Op::Rename, Op::Move, Op::Copy] {
318 let s = serde_json::to_string(&op).unwrap();
319 assert_eq!(serde_json::from_str::<Op>(&s).unwrap(), op);
320 }
321 assert!(serde_json::from_str::<Op>("\"explode\"").is_err());
322 }
323
324 #[test]
325 fn mutation_round_trip_skips_absent_fields() {
326 let m = Mutation {
327 op: Op::Move,
328 new_name: None,
329 dst_root_id: Some(3),
330 dst: Some("docs".into()),
331 overwrite: true,
332 };
333 let s = serde_json::to_string(&m).unwrap();
334 assert!(!s.contains("new_name"));
335 let back: Mutation = serde_json::from_str(&s).unwrap();
336 assert_eq!(back.dst_root_id, Some(3));
337 assert_eq!(back.op, Op::Move);
338 }
339
340 #[test]
341 fn mutation_defaults_missing_fields() {
342 let m: Mutation = serde_json::from_str(r#"{"op":"rename","new_name":"a.txt"}"#).unwrap();
343 assert!(!m.overwrite);
344 assert_eq!(m.dst, None);
345 }
346
347 #[test]
348 fn root_defaults_mode_to_rw() {
349 let r: Root = serde_json::from_str(r#"{"path":"docs"}"#).unwrap();
350 assert_eq!(r.mode, Mode::Rw);
351 }
352
353 #[test]
354 fn me_round_trip() {
355 let me = Me {
356 first_boot: false,
357 user: Some(UserInfo {
358 id: 1,
359 name: "admin".into(),
360 is_admin: true,
361 }),
362 roots: vec![RootInfo {
363 id: 1,
364 name: "root".into(),
365 path: ".".into(),
366 mode: Mode::Rw,
367 }],
368 allow_writable_shares: false,
369 };
370 let s = serde_json::to_string(&me).unwrap();
371 let back: Me = serde_json::from_str(&s).unwrap();
372 assert_eq!(back.roots.len(), 1);
373 }
374}
375