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 /// Profile setting: single click opens entries (off = click selects,
221 /// double click opens).
222 pub single_click_open: bool,
223 /// Preferred UI language tag ("en", "de", "fr"); None = follow the
224 /// browser.
225 pub language: Option<String>,
226}
227
228#[derive(Serialize, Deserialize, Clone)]
229pub struct RootInfo {
230 pub id: i64,
231 pub name: String,
232 pub path: String,
233 pub mode: Mode,
234}
235
236/// GET `{AUTH_ME}`.
237#[derive(Serialize, Deserialize, Clone)]
238pub struct Me {
239 /// True while no users exist yet (first-boot setup).
240 pub first_boot: bool,
241 /// None on first boot.
242 pub user: Option<UserInfo>,
243 pub roots: Vec<RootInfo>,
244 pub allow_writable_shares: bool,
245}
246
247/// GET/POST `{SHARES}`, GET `{SHARE}/{token}`.
248#[derive(Serialize, Deserialize, Clone)]
249pub struct ShareInfo {
250 pub id: i64,
251 pub token: String,
252 /// Display name (file/folder name, or the root's name for ".").
253 pub name: String,
254 pub is_file: bool,
255 pub writable: bool,
256 /// Path relative to the server root.
257 pub target: String,
258 /// RFC 3339 UTC creation time.
259 pub created_at: String,
260 /// RFC 3339 UTC expiry; None = never.
261 pub expires_at: Option<String>,
262 /// Synthetic root id to use in file API calls.
263 pub root_id: i64,
264 /// The file's kind for file shares (None for folder shares, and when
265 /// not sniffed — the public resolve endpoint fills it in).
266 pub kind: Option<FileKind>,
267}
268
269/// GET/POST `{ADMIN_USERS}`, PUT `{ADMIN_USERS}/{id}`.
270#[derive(Serialize, Deserialize, Clone)]
271pub struct AdminUser {
272 pub id: i64,
273 pub name: String,
274 pub is_admin: bool,
275 pub active: bool,
276 pub roots: Vec<RootInfo>,
277}
278
279/// Acknowledges a successful mutation: `{"ok": true}`.
280#[derive(Serialize, Deserialize)]
281pub struct OkResp {
282 pub ok: bool,
283}
284
285/// Upload success: `{"ok": true, "uploaded": n}`.
286#[derive(Serialize, Deserialize)]
287pub struct UploadResp {
288 pub ok: bool,
289 pub uploaded: usize,
290}
291
292/// PUT `?action=content` (editor save): the file's new mtime (unix seconds).
293#[derive(Serialize, Deserialize)]
294pub struct SaveResp {
295 pub ok: bool,
296 pub mtime: i64,
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 /// The serde spellings are the database values too, so they are pinned.
304 #[test]
305 fn mode_wire_format_is_rw_ro() {
306 assert_eq!(serde_json::to_string(&Mode::Rw).unwrap(), "\"rw\"");
307 assert_eq!(serde_json::to_string(&Mode::Ro).unwrap(), "\"ro\"");
308 for m in [Mode::Rw, Mode::Ro] {
309 let s = serde_json::to_string(&m).unwrap();
310 assert_eq!(serde_json::from_str::<Mode>(&s).unwrap(), m);
311 // `as_str`/`from_wire` must agree with serde.
312 assert_eq!(s, format!("\"{}\"", m.as_str()));
313 assert_eq!(Mode::from_wire(m.as_str()), Some(m));
314 }
315 assert_eq!(Mode::from_wire("both"), None);
316 assert!(serde_json::from_str::<Mode>("\"both\"").is_err());
317 assert!(Mode::Rw.is_writable());
318 assert!(!Mode::Ro.is_writable());
319 }
320
321 #[test]
322 fn op_wire_format() {
323 assert_eq!(serde_json::to_string(&Op::Rename).unwrap(), "\"rename\"");
324 assert_eq!(serde_json::to_string(&Op::Move).unwrap(), "\"move\"");
325 assert_eq!(serde_json::to_string(&Op::Copy).unwrap(), "\"copy\"");
326 for op in [Op::Rename, Op::Move, Op::Copy] {
327 let s = serde_json::to_string(&op).unwrap();
328 assert_eq!(serde_json::from_str::<Op>(&s).unwrap(), op);
329 }
330 assert!(serde_json::from_str::<Op>("\"explode\"").is_err());
331 }
332
333 #[test]
334 fn mutation_round_trip_skips_absent_fields() {
335 let m = Mutation {
336 op: Op::Move,
337 new_name: None,
338 dst_root_id: Some(3),
339 dst: Some("docs".into()),
340 overwrite: true,
341 };
342 let s = serde_json::to_string(&m).unwrap();
343 assert!(!s.contains("new_name"));
344 let back: Mutation = serde_json::from_str(&s).unwrap();
345 assert_eq!(back.dst_root_id, Some(3));
346 assert_eq!(back.op, Op::Move);
347 }
348
349 #[test]
350 fn mutation_defaults_missing_fields() {
351 let m: Mutation = serde_json::from_str(r#"{"op":"rename","new_name":"a.txt"}"#).unwrap();
352 assert!(!m.overwrite);
353 assert_eq!(m.dst, None);
354 }
355
356 #[test]
357 fn root_defaults_mode_to_rw() {
358 let r: Root = serde_json::from_str(r#"{"path":"docs"}"#).unwrap();
359 assert_eq!(r.mode, Mode::Rw);
360 }
361
362 #[test]
363 fn me_round_trip() {
364 let me = Me {
365 first_boot: false,
366 user: Some(UserInfo {
367 id: 1,
368 name: "admin".into(),
369 is_admin: true,
370 single_click_open: false,
371 language: None,
372 }),
373 roots: vec![RootInfo {
374 id: 1,
375 name: "root".into(),
376 path: ".".into(),
377 mode: Mode::Rw,
378 }],
379 allow_writable_shares: false,
380 };
381 let s = serde_json::to_string(&me).unwrap();
382 let back: Me = serde_json::from_str(&s).unwrap();
383 assert_eq!(back.roots.len(), 1);
384 }
385}
386