Skip to main content

brep_plm/api/
workspace.rs

1//! Workspaces over HTTP. The rules are in [`crate::workspace`].
2//!
3//! A file upload is the raw bytes as the body, as for attachments
4//! ([`super::attachments`]): its media type as `Content-Type`, its folder and
5//! name in the query string. It streams to disk and is refused with `413` the
6//! moment it passes the attachment limit.
7
8use axum::body::Body;
9use axum::extract::{Path, Query, State};
10use axum::http::HeaderMap;
11use axum::response::Response;
12use axum::Json;
13use serde::Deserialize;
14use serde_json::{json, Value};
15
16use super::attachments::{receive, stream_blob};
17use super::{blocking, require_user, Shared};
18use crate::workspace::Promote;
19use crate::Error;
20
21fn media_type(headers: &HeaderMap) -> String {
22    headers
23        .get(axum::http::header::CONTENT_TYPE)
24        .and_then(|v| v.to_str().ok())
25        .unwrap_or("")
26        .to_string()
27}
28
29fn seq(db: &Shared) -> u64 {
30    db.read(|state| state.seq)
31}
32
33/// The workspaces the caller may open, their own first.
34pub async fn list_workspaces(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Value>, Error> {
35    let user = require_user(&db, &headers)?;
36    let browsable = db.read(|state| state.settings.workspaces_browsable);
37    Ok(Json(json!({ "workspaces": db.workspaces(&user), "browsable": browsable })))
38}
39
40#[derive(Debug, Deserialize, Default)]
41pub struct FolderQuery {
42    /// A user id or username; empty is the caller.
43    #[serde(default)]
44    pub owner: String,
45    /// A folder id; empty is the top.
46    #[serde(default)]
47    pub parent: String,
48}
49
50/// The entries in one folder.
51pub async fn list_folder(
52    State(db): State<Shared>,
53    headers: HeaderMap,
54    Query(query): Query<FolderQuery>,
55) -> Result<Json<Value>, Error> {
56    let user = require_user(&db, &headers)?;
57    let entries = db.workspace_folder(&user, &query.owner, &query.parent)?;
58    Ok(Json(json!({ "entries": entries, "seq": seq(&db) })))
59}
60
61#[derive(Debug, Deserialize, Default)]
62pub struct LinksQuery {
63    /// A part id or number.
64    #[serde(default)]
65    pub part: String,
66}
67
68/// The folders of the caller's own workspace that link a part (`?part=`).
69pub async fn folders_linking(
70    State(db): State<Shared>,
71    headers: HeaderMap,
72    Query(query): Query<LinksQuery>,
73) -> Result<Json<Value>, Error> {
74    let user = require_user(&db, &headers)?;
75    let folders = db.folders_linking(&user, &query.part)?;
76    Ok(Json(json!({ "folders": folders })))
77}
78
79/// Every folder the caller may read, linked anywhere or nowhere.
80pub async fn list_folders(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Value>, Error> {
81    let user = require_user(&db, &headers)?;
82    Ok(Json(json!({ "folders": db.workspace_folders(&user), "seq": seq(&db) })))
83}
84
85#[derive(Debug, Deserialize, Default)]
86pub struct NewFolder {
87    #[serde(default)]
88    pub parent: String,
89    pub name: String,
90}
91
92pub async fn create_folder(
93    State(db): State<Shared>,
94    headers: HeaderMap,
95    Json(body): Json<NewFolder>,
96) -> Result<Json<Value>, Error> {
97    let user = require_user(&db, &headers)?;
98    let made = blocking({
99        let db = db.clone();
100        move || db.create_folder(&user, &body.parent, &body.name)
101    })
102    .await?;
103    Ok(Json(json!({ "ok": true, "entry": made, "seq": seq(&db) })))
104}
105
106#[derive(Debug, Deserialize, Default)]
107pub struct NewLink {
108    #[serde(default)]
109    pub parent: String,
110    /// Empty: the part's number.
111    #[serde(default)]
112    pub name: String,
113    /// A part id or number.
114    #[serde(default)]
115    pub part: String,
116    /// A revision id or label to pin to; empty follows the newest.
117    #[serde(default)]
118    pub revision: String,
119    /// Instead of a part: a folder (or a link to one) to link, the same
120    /// folder in each place.
121    #[serde(default)]
122    pub folder: String,
123    /// With `folder`: a user id or username whose Home gets the link, at
124    /// its top (the folder's owner only). Empty: the caller's `parent`.
125    #[serde(default)]
126    pub home: String,
127    /// Instead of a part or folder: a file (or a link to one).
128    #[serde(default)]
129    pub file: String,
130    /// Instead: an attachment, on the part `part` (and revision `revision`,
131    /// when it is a revision's).
132    #[serde(default)]
133    pub attachment: String,
134}
135
136pub async fn create_link(
137    State(db): State<Shared>,
138    headers: HeaderMap,
139    Json(body): Json<NewLink>,
140) -> Result<Json<Value>, Error> {
141    let user = require_user(&db, &headers)?;
142    let made = blocking({
143        let db = db.clone();
144        move || {
145            if !body.folder.trim().is_empty() {
146                db.link_folder(&user, &body.parent, &body.folder, &body.home)
147            } else if !body.file.trim().is_empty() {
148                db.link_file(&user, &body.parent, &body.file)
149            } else if !body.attachment.trim().is_empty() {
150                db.link_attachment(&user, &body.parent, &body.attachment, &body.part, &body.revision)
151            } else {
152                db.create_link(&user, &body.parent, &body.name, &body.part, &body.revision)
153            }
154        }
155    })
156    .await?;
157    Ok(Json(json!({ "ok": true, "entry": made, "seq": seq(&db) })))
158}
159
160#[derive(Debug, Deserialize, Default)]
161pub struct NewCopy {
162    #[serde(default)]
163    pub parent: String,
164    /// One of these: a folder, a file, an attachment (with `part` and
165    /// `revision` saying whose), or a part (with `revision`, which model).
166    #[serde(default)]
167    pub folder: String,
168    #[serde(default)]
169    pub file: String,
170    #[serde(default)]
171    pub attachment: String,
172    #[serde(default)]
173    pub part: String,
174    #[serde(default)]
175    pub revision: String,
176    /// For a part whose type takes a typed number: the copy's number.
177    #[serde(default)]
178    pub number: String,
179}
180
181/// Paste a new unique copy of a folder, file, attachment or part into a
182/// folder the caller owns (or their Home).
183pub async fn create_copy(
184    State(db): State<Shared>,
185    headers: HeaderMap,
186    Json(body): Json<NewCopy>,
187) -> Result<Json<Value>, Error> {
188    use crate::workspace::CopyOf;
189    let user = require_user(&db, &headers)?;
190    let answer = blocking({
191        let db = db.clone();
192        move || {
193            let what = if !body.folder.trim().is_empty() {
194                CopyOf::Folder(body.folder)
195            } else if !body.file.trim().is_empty() {
196                CopyOf::File(body.file)
197            } else if !body.attachment.trim().is_empty() {
198                CopyOf::Attachment { id: body.attachment, part: body.part, revision: body.revision }
199            } else if !body.part.trim().is_empty() {
200                let part = db.copy_part(&user, &body.parent, &body.part, &body.revision, &body.number)?;
201                return Ok(json!({ "part": part }));
202            } else {
203                return Err(Error::bad_request("name a folder, file, attachment or part to copy"));
204            };
205            db.paste_copy(&user, &body.parent, &what).map(|entry| json!({ "entry": entry }))
206        }
207    })
208    .await?;
209    let mut answer = answer;
210    answer["ok"] = json!(true);
211    answer["seq"] = json!(seq(&db));
212    Ok(Json(answer))
213}
214
215/// Every file the caller may read, linked anywhere or nowhere.
216pub async fn list_files(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Value>, Error> {
217    let user = require_user(&db, &headers)?;
218    Ok(Json(json!({ "files": db.workspace_files(&user), "seq": seq(&db) })))
219}
220
221#[derive(Debug, Deserialize, Default)]
222pub struct NewFile {
223    #[serde(default)]
224    pub parent: String,
225    #[serde(default)]
226    pub name: String,
227}
228
229/// Upload a new file: version 1.
230pub async fn create_file(
231    State(db): State<Shared>,
232    headers: HeaderMap,
233    Query(query): Query<NewFile>,
234    body: Body,
235) -> Result<Json<Value>, Error> {
236    let user = require_user(&db, &headers)?;
237    // Refuse a bad name before reading the bytes.
238    crate::workspace::clean_name(&query.name)?;
239    let staged = receive(&db, &headers, body).await?;
240    let media = media_type(&headers);
241    let made = blocking({
242        let db = db.clone();
243        move || db.create_file(&user, &query.parent, &query.name, &media, staged)
244    })
245    .await?;
246    Ok(Json(json!({ "ok": true, "entry": made, "seq": seq(&db) })))
247}
248
249/// One entry.
250pub async fn get_entry(
251    State(db): State<Shared>,
252    headers: HeaderMap,
253    Path(id): Path<String>,
254) -> Result<Json<Value>, Error> {
255    let user = require_user(&db, &headers)?;
256    Ok(Json(json!({ "entry": db.workspace_entry(&user, &id)? })))
257}
258
259/// Rename, move, or pin / unpin a link.
260pub async fn update_entry(
261    State(db): State<Shared>,
262    headers: HeaderMap,
263    Path(id): Path<String>,
264    Json(body): Json<Value>,
265) -> Result<Json<Value>, Error> {
266    let user = require_user(&db, &headers)?;
267    let changed = blocking({
268        let db = db.clone();
269        move || db.update_entry(&user, &id, &body)
270    })
271    .await?;
272    Ok(Json(json!({ "ok": true, "entry": changed, "seq": seq(&db) })))
273}
274
275#[derive(Debug, Deserialize, Default)]
276pub struct DeleteQuery {
277    /// Delete a folder with everything in it.
278    #[serde(default)]
279    pub recursive: bool,
280}
281
282/// Remove an entry. Never a part or a revision.
283pub async fn delete_entry(
284    State(db): State<Shared>,
285    headers: HeaderMap,
286    Path(id): Path<String>,
287    Query(query): Query<DeleteQuery>,
288) -> Result<Json<Value>, Error> {
289    let user = require_user(&db, &headers)?;
290    let removed = blocking({
291        let db = db.clone();
292        move || db.delete_entry(&user, &id, query.recursive)
293    })
294    .await?;
295    Ok(Json(json!({ "ok": true, "removed": removed, "seq": seq(&db) })))
296}
297
298/// Replace a file's bytes; the old version is kept.
299pub async fn replace_file(
300    State(db): State<Shared>,
301    headers: HeaderMap,
302    Path(id): Path<String>,
303    body: Body,
304) -> Result<Json<Value>, Error> {
305    let user = require_user(&db, &headers)?;
306    // Refuse a caller who may not write before reading the bytes.
307    db.read(|state| crate::workspace::check_may_change(state, &user, &id))?;
308    let expected = headers.get(axum::http::header::IF_MATCH).and_then(|v| v.to_str().ok()).map(|v| v.trim_matches('"').to_string());
309    if expected.as_ref().is_some_and(|v| !crate::attach::is_sha256(v)) { return Err(Error::bad_request("If-Match must name the current file hash")); }
310    let staged = super::attachments::receive_with_empty(&db, &headers, body, true).await?;
311    let media = media_type(&headers);
312    let changed = blocking({
313        let db = db.clone();
314        move || db.replace_file_checked(&user, &id, &media, staged, expected)
315    })
316    .await?;
317    Ok(Json(json!({ "ok": true, "entry": changed, "seq": seq(&db) })))
318}
319
320#[derive(Debug, Deserialize, Default)]
321pub struct ContentQuery {
322    /// Which version; absent or 0 is the current one.
323    #[serde(default)]
324    pub version: u32,
325    #[serde(default)]
326    pub inline: bool,
327}
328
329/// Download a file, or one of its versions.
330pub async fn download(
331    State(db): State<Shared>,
332    headers: HeaderMap,
333    Path(id): Path<String>,
334    Query(query): Query<ContentQuery>,
335) -> Result<Response, Error> {
336    let user = require_user(&db, &headers)?;
337    let (name, version) = db.workspace_file(&user, &id, query.version)?;
338    stream_blob(&db, &name, &version.media_type, &version.sha256, version.size, query.inline).await
339}
340
341/// A file's versions, oldest first.
342pub async fn versions(
343    State(db): State<Shared>,
344    headers: HeaderMap,
345    Path(id): Path<String>,
346) -> Result<Json<Value>, Error> {
347    let user = require_user(&db, &headers)?;
348    Ok(Json(json!({ "versions": db.workspace_versions(&user, &id)? })))
349}
350
351/// Make an old version current again (as a new version).
352pub async fn restore(
353    State(db): State<Shared>,
354    headers: HeaderMap,
355    Path((id, version)): Path<(String, u32)>,
356) -> Result<Json<Value>, Error> {
357    let user = require_user(&db, &headers)?;
358    let changed = blocking({
359        let db = db.clone();
360        move || db.restore_version(&user, &id, version)
361    })
362    .await?;
363    Ok(Json(json!({ "ok": true, "entry": changed, "seq": seq(&db) })))
364}
365
366#[derive(Debug, Deserialize, Default)]
367pub struct PromoteBody {
368    /// A part id or number.
369    pub part: String,
370    /// A revision id or label; empty attaches to the part.
371    #[serde(default)]
372    pub revision: String,
373    #[serde(default)]
374    pub version: u32,
375    #[serde(default)]
376    pub name: String,
377    #[serde(default)]
378    pub kind: String,
379    #[serde(default)]
380    pub note: String,
381}
382
383/// Promote a file to an attachment on a part or revision.
384pub async fn promote(
385    State(db): State<Shared>,
386    headers: HeaderMap,
387    Path(id): Path<String>,
388    Json(body): Json<PromoteBody>,
389) -> Result<Json<Value>, Error> {
390    let user = require_user(&db, &headers)?;
391    let ask = Promote {
392        part: body.part,
393        revision: body.revision,
394        version: body.version,
395        name: body.name,
396        kind: body.kind,
397        note: body.note,
398    };
399    let made = blocking({
400        let db = db.clone();
401        move || db.promote(&user, &id, &ask)
402    })
403    .await?;
404    Ok(Json(json!({ "ok": true, "attachment": made, "seq": seq(&db) })))
405}