Skip to main content

brep_plm/
player.rs

1//! Serving the manufacturing instructions player per instructions revision.
2//!
3//! The player page is TRUSTED code: the template of the `BREP_instructions`
4//! crate ([`brep_instructions::player`]), served under a policy of its own
5//! with a nonce per response. What a CAD client uploads is only DATA (the
6//! crate's `PlayerData` JSON: steps, meshes, poses). Authors never
7//! upload HTML: a page with their script on the PLM's origin would run with
8//! every viewer's session.
9//!
10//! - **Keyed by the document**, like a thumbnail ([`crate::thumbnail`]): the
11//!   upload names the revision's `content_hash` it was made from, and the
12//!   data is served only while that is still the revision's. An author
13//!   uploads it; no lock is needed, so a newer player can re-make a
14//!   released revision's data.
15//! - **Stored as a blob** of the attachment store ([`crate::attach`]),
16//!   referenced from the revision and in every backup.
17//! - **`/instructions/<number>/<rev>`** serves the page to anyone signed in,
18//!   `?mode=shop|customer`, and `&job=JOB…` in shop mode signs that job's
19//!   steps ([`crate::jobs`]).
20//! - **Customer links** (`/s/<token>`) serve a RELEASED revision's player in
21//!   customer mode to anyone holding the link: no sign-in, no sign-off, and
22//!   nothing but that revision's player data. The token is shown once and
23//!   kept only as its SHA-256; a link is revoked by deleting it.
24
25use crate::attach::{self, Staged};
26use crate::db::{now, Db, State};
27use crate::model::{DocumentClass, Lifecycle, Part, PlayerArtifact, Revision, Share, User};
28use crate::Error;
29
30/// The largest player data, in bytes (meshes for a few hundred parts).
31pub const MAX_BYTES: u64 = 64 * 1024 * 1024;
32
33/// The policy the player page is served under: its one script and one style
34/// block by nonce, pictures from the data or this server, and requests only
35/// back to this server.
36pub fn policy(nonce: &str) -> String {
37    format!(
38        "default-src 'none'; script-src 'nonce-{nonce}'; style-src 'nonce-{nonce}'; img-src 'self' data:; \
39         connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
40    )
41}
42
43/// The data to serve for a revision: present and made from its current document.
44pub fn current(revision: &Revision) -> Option<&PlayerArtifact> {
45    revision.player.as_ref().filter(|p| !revision.content_hash.is_empty() && p.content_hash == revision.content_hash)
46}
47
48/// The id a share is listed and revoked by: the first 12 hex of its hash.
49fn share_id(token_sha256: &str) -> String {
50    token_sha256[..12].to_string()
51}
52
53/// A part whose revisions carry player data: manufacturing instructions (the
54/// instructions player) or an ordinary part (a motion study's player, made
55/// by the CAD app from the assembly's active study). Families and templates
56/// have none.
57fn playable<'a>(state: &'a State, part_key: &str, revision_key: &str) -> Result<(&'a Part, &'a Revision), Error> {
58    let part = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
59    if !matches!(part.document_class, DocumentClass::Instructions | DocumentClass::Normal) {
60        return Err(Error::bad_request(format!("{} has no player: it is a {}", part.number, part.document_class.as_str())));
61    }
62    let revision = crate::bom::find_revision(part, revision_key).ok_or_else(|| Error::not_found("revision"))?;
63    Ok((part, revision))
64}
65
66fn instructions<'a>(state: &'a State, part_key: &str, revision_key: &str) -> Result<(&'a Part, &'a Revision), Error> {
67    let part = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
68    if part.document_class != DocumentClass::Instructions {
69        return Err(Error::bad_request(format!("{} is not manufacturing instructions", part.number)));
70    }
71    let revision = crate::bom::find_revision(part, revision_key).ok_or_else(|| Error::not_found("revision"))?;
72    Ok((part, revision))
73}
74
75impl Db {
76    /// Keep `staged` (already checked to be player data) as the player data
77    /// of a revision — instructions, or an ordinary part's motion study —
78    /// made from document `claimed`.
79    pub fn put_player_data(&self, user: &User, part_key: &str, revision_key: &str, staged: Staged, claimed: &str) -> Result<PlayerArtifact, Error> {
80        if !user.can_author() {
81            return Err(Error::forbidden("player data is uploaded by an author"));
82        }
83        let root = self.root().to_path_buf();
84        let (part_key, revision_key, claimed, user_id) = (part_key.to_string(), revision_key.to_string(), claimed.trim().to_string(), user.id.clone());
85        self.mutate(move |state| {
86            let (part, revision) = playable(state, &part_key, &revision_key)?;
87            let (part_id, revision_id) = (part.id.clone(), revision.id.clone());
88            if revision.content_hash.is_empty() {
89                return Err(Error::conflict(format!("{} revision {} has no document to play", part.number, revision.label)));
90            }
91            if claimed != revision.content_hash {
92                return Err(Error::conflict(format!(
93                    "the player data was made from another document than {} revision {} holds now: make it again",
94                    part.number, revision.label
95                )));
96            }
97            attach::place(&root, &staged)?;
98            let artifact = PlayerArtifact { sha256: staged.sha256.clone(), size: staged.size, content_hash: claimed, uploaded_by: user_id, uploaded_at: now() };
99            let revision = state.parts.get_mut(&part_id).and_then(|p| p.revision_mut(&revision_id)).ok_or_else(|| Error::not_found("revision"))?;
100            let old = revision.player.replace(artifact.clone());
101            if let Some(old) = old.filter(|o| o.sha256 != artifact.sha256) {
102                attach::remove_if_unreferenced(state, &root, &old.sha256)?;
103            }
104            Ok(artifact)
105        })
106    }
107
108    /// A revision's current player data (instructions, or an ordinary part's
109    /// motion study), with its part and revision ids; `None` when there is
110    /// none or it is stale.
111    pub fn player_data(&self, part_key: &str, revision_key: &str) -> Result<(String, String, Option<PlayerArtifact>), Error> {
112        self.read(|state| {
113            let (part, revision) = playable(state, part_key, revision_key)?;
114            Ok((part.id.clone(), revision.id.clone(), current(revision).cloned()))
115        })
116    }
117
118    /// The same for manufacturing instructions only: the `/instructions/…`
119    /// page refuses an ordinary part (its study plays at `/motion/…`).
120    pub fn instructions_player_data(&self, part_key: &str, revision_key: &str) -> Result<(String, String, Option<PlayerArtifact>), Error> {
121        self.read(|state| {
122            let (part, revision) = instructions(state, part_key, revision_key)?;
123            Ok((part.id.clone(), revision.id.clone(), current(revision).cloned()))
124        })
125    }
126
127    /// Make a customer link to a released instructions revision: the share
128    /// and its token, which is never shown again.
129    pub fn create_share(&self, user: &User, part_key: &str, revision_key: &str, label: &str) -> Result<(Share, String), Error> {
130        if !user.can_author() {
131            return Err(Error::forbidden("a customer link is made by an author"));
132        }
133        let label = label.trim().to_string();
134        if label.chars().count() > 200 {
135            return Err(Error::bad_request("a link's label is at most 200 characters"));
136        }
137        let token = format!("{}{}", crate::auth::random_token(16), crate::auth::random_token(16));
138        let token_sha256 = crate::auth::content_hash(&token);
139        let (part_key, revision_key, user_id) = (part_key.to_string(), revision_key.to_string(), user.id.clone());
140        let share = self.mutate(move |state| {
141            let (part, revision) = instructions(state, &part_key, &revision_key)?;
142            if revision.lifecycle != Lifecycle::Released {
143                return Err(Error::conflict(format!(
144                    "{} revision {} is {}: customers get released instructions only",
145                    part.number,
146                    revision.label,
147                    revision.lifecycle.as_str()
148                )));
149            }
150            let (part_id, revision_id) = (part.id.clone(), revision.id.clone());
151            let share = Share { id: share_id(&token_sha256), token_sha256, label, created_by: user_id, created_at: now() };
152            let revision = state.parts.get_mut(&part_id).and_then(|p| p.revision_mut(&revision_id)).ok_or_else(|| Error::not_found("revision"))?;
153            revision.shares.push(share.clone());
154            Ok(share)
155        })?;
156        Ok((share, token))
157    }
158
159    pub fn revoke_share(&self, part_key: &str, revision_key: &str, id: &str) -> Result<(), Error> {
160        let (part_key, revision_key, id) = (part_key.to_string(), revision_key.to_string(), id.to_string());
161        self.mutate(move |state| {
162            let (part, revision) = instructions(state, &part_key, &revision_key)?;
163            if !revision.shares.iter().any(|s| s.id == id) {
164                return Err(Error::not_found("customer link"));
165            }
166            let (part_id, revision_id) = (part.id.clone(), revision.id.clone());
167            let revision = state.parts.get_mut(&part_id).and_then(|p| p.revision_mut(&revision_id)).ok_or_else(|| Error::not_found("revision"))?;
168            revision.shares.retain(|s| s.id != id);
169            Ok(())
170        })
171    }
172
173    /// What a customer link opens: its revision's current player data, while
174    /// the revision is released. `None` for an unknown or revoked token.
175    pub fn shared_player(&self, token: &str) -> Option<(String, Option<PlayerArtifact>)> {
176        if token.len() < 40 || !token.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
177            return None;
178        }
179        let hash = crate::auth::content_hash(token);
180        self.read(|state| {
181            state.parts.iter().filter(|p| p.document_class == DocumentClass::Instructions).find_map(|part| {
182                part.revisions
183                    .iter()
184                    .find(|r| r.lifecycle == Lifecycle::Released && r.shares.iter().any(|s| s.token_sha256 == hash))
185                    .map(|r| (format!("{} rev {}", part.number, r.label), current(r).cloned()))
186            })
187        })
188    }
189}