Compare commits

...

5 Commits

Author SHA1 Message Date
codex fc9fcdd0d4 Keep the 0.3.1 web and Android release marked alpha 2026-11-23 01:41:16 +00:00
codex a63458c94e Prepare Web Slicer 0.3.1 with desktop Bambu sign-in 2026-11-23 00:18:03 +00:00
codex 27cbe5a04b Improve filament and Bambu workflows and add external model import 2026-11-22 21:03:09 +00:00
Claude 145ec0f43a docs: upstream merges must surface new GUI options in the web client
Our GUI is a separate web client, not OrcaSlicer's desktop GUI, so merging the
C++ does not make a new upstream setting appear for our users. Document the
mechanism (schema from PrintConfig.cpp, placement from setting-layout.json
generated off Tab.cpp) and require regenerating the layout and verifying new
options render — or recording a deliberate deferral — after each merge.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CbKxbSeHpxVhmWEwU8U2vE
2026-11-22 18:42:50 +00:00
Claude 8b18bd58ac Android: update stage comment for the two-APK release
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CbKxbSeHpxVhmWEwU8U2vE
2026-11-22 18:35:04 +00:00
58 changed files with 2649 additions and 173 deletions
+5
View File
@@ -70,3 +70,8 @@ web/frontend/dist-demo
# Persistent application data beside compose.yaml.
/data/
# Package the desktop helper from committed sources in the web image.
desktop/bambu-login/node_modules
desktop/bambu-login/dist
web/frontend/public/bambu-login/*.zip
+1 -1
View File
@@ -1,7 +1,7 @@
# Copy to .env. Runtime state belongs in ./data beside compose.yaml, not Git.
# The maintainer publishes app + web with the same immutable version tag.
ORCA_IMAGE_PREFIX=gitea.labus.uk/karol/web-slicer
ORCA_IMAGE_TAG=0.2.2-alpha
ORCA_IMAGE_TAG=0.3.1-alpha
WEB_PORT=8080
LAN_BIND=0.0.0.0
+12 -9
View File
@@ -149,7 +149,7 @@ models can exceed these defaults. Build requirements are separate; see
## Getting started
The current image version is `0.2.2-alpha`, an alpha for evaluation. Images
The current image version is `0.3.1-alpha`. Images
are public and can be pulled without registry authentication.
Install Docker Engine and Compose v2. Put [compose.yaml](compose.yaml) and
@@ -211,14 +211,12 @@ save G-code with no server, account or network. It can also drive printers on
your LAN — Bambu Lab in Developer Mode, Anycubic Kobra, Moonraker and the other
hosts the web client supports.
The current app version is `0.3.0-alpha`, an alpha for evaluation. Install it by
side-loading the APK from the [latest release](https://gitea.labus.uk/karol/web-slicer/releases)
(enable "install unknown apps" for your browser or file manager); it is not on
any app store. Two builds are published:
The current Android version is `0.3.1-alpha`. Enable "install unknown apps"
for your browser or file manager to sideload one of the two APKs:
- `web-slicer-<version>-arm64.apk` — the standard app (offline slicing and LAN
- [Standard APK](https://gitea.labus.uk/api/packages/karol/generic/web-slicer-android/0.3.1-alpha/web-slicer-0.3.1-alpha-arm64.apk) — the standard app (offline slicing and LAN
printing). Most users want this one.
- `web-slicer-<version>-cloud-arm64.apk` — additionally bundles the third-party
- [Bambu Cloud APK](https://gitea.labus.uk/api/packages/karol/generic/web-slicer-android/0.3.1-alpha/web-slicer-0.3.1-alpha-cloud-arm64.apk) — additionally bundles the third-party
[open-bamboo-networking](https://gitea.labus.uk/karol/open-bamboo-networking)
plugin (AGPL-3.0) for Bambu Lab account sign-in, cloud printer status and
control, and cloud printing. It ships no Bambu keys: printers with command
@@ -236,7 +234,7 @@ Copy [.env.example](.env.example) to `.env`. Do not commit the edited file.
| Variable | Default | Purpose |
| --- | --- | --- |
| `ORCA_IMAGE_PREFIX` | `gitea.labus.uk/karol/web-slicer` | Shared image prefix; services append `-app`, `-web` and optional `-demo`. |
| `ORCA_IMAGE_TAG` | `0.2.2-alpha` | Matching release version for all images; alpha prerelease. |
| `ORCA_IMAGE_TAG` | `0.3.1-alpha` | Matching release version for all images. |
| `WEB_PORT` | `8080` | Published HTTP port. |
| `LAN_BIND` | `0.0.0.0` | Host bind address; use `127.0.0.1` for a proxy on the same host. |
| `DEMO_PORT` / `DEMO_BIND` | `8082` / `127.0.0.1` | Separate static demo, enabled with the `demo` Compose profile. |
@@ -366,7 +364,12 @@ git merge --no-commit upstream/main
For an existing `upstream`, skip `remote add`. Resolve conflicts and refresh
`README.upstream.md` from the reviewed upstream revision while retaining this
fork README. Before merging, check headless/desktop builds, 3MF compatibility,
profiles, generated settings/locales, API contracts and browser preview. See
profiles, generated settings/locales, API contracts and browser preview.
This fork's GUI is a separate web client, not OrcaSlicer's desktop GUI, so a
merge that only builds is not finished: new upstream options must be surfaced in
the web client (regenerate the settings layout and confirm they render), never
left behind because the C++ merged cleanly. See
[upstream maintenance](docs/upstream-maintenance.md).
## Documentation
+2 -2
View File
@@ -14,8 +14,8 @@ android {
applicationId = "uk.labus.webslicer"
minSdk = 29
targetSdk = 35
versionCode = 2
versionName = "0.3.0-alpha"
versionCode = 3
versionName = "0.3.1-alpha"
ndk { abiFilters += "arm64-v8a" }
}
sourceSets["main"].assets.srcDir(stage.resolve("assets"))
+32 -5
View File
@@ -127,14 +127,41 @@ Resulting split:
and MQTT. The plugin ships only in the separate cloud-enabled build, never in
the standard APK (see "Distribution decision": both are published as distinct
release APKs).
- **Web client/server:** the server runs the same host and plugin (x86_64), but
the browser cannot capture the login. It needs a device-side helper (for
example the Android app signing in on the server's behalf, or a one-off
DevTools user-agent override plus a bridge snippet for testing). Deferred until
the Android path works.
- **Web client/server:** the browser pairs a
[portable desktop helper](../desktop/bambu-login/README.md) with the user's
Web Slicer session. The helper opens Bambu's sign-in page in an isolated
window and delivers the result to the confirmed HTTPS server. Pairing links
expire after ten minutes and are single-use. In authenticated installations
each Web Slicer user has a private Bambu runtime directory. A saved physical
cloud printer uses its owner's Bambu session and follows normal printer grants.
Existing single-instance sessions require a fresh sign-in when switching
to authenticated mode.
### Device panel over the account
In Printers, **Add from Bambu Lab account** opens the account printer list.
The account dialog also offers **Add to printers** beside each device. Select
the nozzle preset in the printer wizard and save the cloud connection without
entering a LAN address or access code. The connection editor exposes
**Bambu Lab cloud** as its own host choice and reports when the build lacks
cloud support.
**Import Bambu Lab presets** opens the preset import review. The native host
downloads personal printer, process and filament presets through the plugin.
Selected presets become shared templates on confirmation. Account preset
synchronization is enabled by default after sign-in in single-user mode. In
authenticated server mode, administrators can explicitly review personal
presets before importing them into the shared template catalogue. The single-user
backend checks the
account periodically and publishes imported presets as shared template
revisions. Edits to a linked template are sent back to the corresponding
Bambu preset. When both copies changed, or a local preset already uses the
name, the sync reports a conflict and preserves both copies. New unlinked
local templates and deletions stay local. You can pause sync or request an
immediate check in the account dialog. Owned presets and open projects keep
their settings. Cloud print from the account
dialog uses the external spool.
A saved Bambu connection has `bambu_transport`: `lan` (the printer's own MQTT
broker, Developer Mode) or `cloud` (the signed-in account). A cloud connection
stores only the serial number and runs the same panel code as LAN
+3 -3
View File
@@ -22,9 +22,9 @@ flags=(-O2 -I"$py/include/python$ver" -L"$py/lib" -lpython$ver -Wl,-z,max-page-s
"$bin/aarch64-linux-android29-clang" -shared -fPIC android/native/pyhost.c "${flags[@]}" -llog -o "$libs/libpyhost.so"
"$bin/aarch64-linux-android29-clang" -fPIE -pie android/native/pylauncher.c "${flags[@]}" -o "$libs/libpylauncher.so"
"$bin/llvm-strip" --strip-unneeded -o "$libs/liborca_headless.so" build/android-headless/src/headless/orca-headless
# Optional Bambu cloud sign-in, for the cloud sideload build only (never the default
# or a public APK): built by android/scripts/build-bambu-cloud.sh. The plugin is
# third-party AGPL code; see android/cloud-and-connectivity.md.
# Optional Bambu cloud sign-in, for the -cloud build only (never the standard APK):
# built by android/scripts/build-bambu-cloud.sh. The plugin is third-party AGPL
# code; see android/cloud-and-connectivity.md for the distribution decision.
if [ "${ORCA_ANDROID_BAMBU_CLOUD:-0}" = 1 ]; then
say "Bambu cloud (sideload build)"
cp build/android-cloud/orca-bambu-cloud "$libs/libbambu_cloud_host.so"
+3 -3
View File
@@ -1,6 +1,6 @@
services:
app:
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-app:${ORCA_IMAGE_TAG:-0.2.2-alpha}
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-app:${ORCA_IMAGE_TAG:-0.3.1-alpha}
init: true
restart: unless-stopped
logging:
@@ -67,7 +67,7 @@ services:
interval: 30s
timeout: 5s
retries: 3
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-web:${ORCA_IMAGE_TAG:-0.2.2-alpha}
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-web:${ORCA_IMAGE_TAG:-0.3.1-alpha}
restart: unless-stopped
logging:
driver: json-file
@@ -81,7 +81,7 @@ services:
condition: service_healthy
demo:
profiles: [demo]
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-demo:${ORCA_IMAGE_TAG:-0.2.2-alpha}
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-demo:${ORCA_IMAGE_TAG:-0.3.1-alpha}
restart: unless-stopped
read_only: true
cpus: 0.25
+2
View File
@@ -0,0 +1,2 @@
node_modules/
dist/
+33
View File
@@ -0,0 +1,33 @@
# Web Slicer Bambu Login
This portable helper pairs a Bambu Lab login with an HTTPS Web Slicer
instance configured for Bambu Cloud and local authentication.
It uses an isolated browser window for the Bambu Lab sign-in page.
The signed-in Web Slicer user generates a single-use pairing link
that expires after ten minutes. The desktop helper sends the login result to
the confirmed server over HTTPS and keeps no local Bambu session after closing.
In Web Slicer open **Bambu Lab account → Desktop helper**. Download the archive for your system
and select **Create pairing link**.
Copy the pairing link, paste it into the helper and confirm the server address.
Return to Web Slicer after the helper confirms the account is connected.
## Packaging
With Node.js and npm installed, run from this directory:
```sh
npm ci
npm run package -- --platform=linux --arch=x64
npm run package -- --platform=win32 --arch=x64
npm run package -- --platform=darwin --arch=arm64
```
To make the archives available in the account dialog, serve them under
`/bambu-login/` as `WebSlicerBambuLogin-linux-x64.zip` and
`WebSlicerBambuLogin-win32-x64.zip`. Archive the entire generated directory
from `dist/`. Run
`WebSlicerBambuLogin` on Linux, `WebSlicerBambuLogin.exe` on Windows or
`WebSlicerBambuLogin.app` on macOS. Use `--arch=x64` for Intel Macs.
Packages generated with these commands are development artifacts. Production
distribution should use platform code signing and macOS notarization.
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Web Slicer Bambu Login</title>
<link rel="stylesheet" href="style.css">
<h1>Connect Bambu Lab to Web Slicer</h1>
<form>
<label for="link">Pairing link from Web Slicer</label>
<input id="link" type="url" autocomplete="off" required autofocus>
<button type="submit">Open Bambu Lab sign-in</button>
</form>
<p role="status" id="status"></p>
<script src="setup.js"></script>
</html>
+118
View File
@@ -0,0 +1,118 @@
const {app, BrowserWindow, dialog, ipcMain, nativeTheme, session} = require('electron');
const path = require('node:path');
const officialSignIn = 'https://bambulab.com/sign-in';
const officialOrigins = new Set(['https://bambulab.com', 'https://www.bambulab.com']);
const preferences = {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
sandbox: true,
nodeIntegration: false
};
let setup, signIn, pairing, sending;
function parseLink(value) {
const url = new URL(value.trim());
const params = new URLSearchParams(url.hash.slice(1));
const code = params.get('bambu_pairing');
const version = params.get('version');
if (url.protocol !== 'https:' || url.username || url.password || !url.pathname.endsWith('/bambu-cloud/desktop-login/redeem') ||
url.search || !code || !/^[A-Za-z0-9_-]{43}$/.test(code))
throw new Error('Paste the HTTPS pairing link from Web Slicer.');
url.hash = '';
return {origin: url.origin, endpoint: url.href, code, version: /^\d{2}(\.\d{2}){2,3}$/.test(version ?? '') ? version : '02.09.01.99'};
}
function openSignIn() {
const partition = session.fromPartition('bambu-' + crypto.randomUUID());
partition.setPermissionRequestHandler((_contents, _permission, callback) => callback(false));
partition.setPermissionCheckHandler(() => false);
partition.on('will-download', event => event.preventDefault());
signIn = new BrowserWindow({title: 'Bambu Lab sign-in', width: 820, height: 760,
webPreferences: {...preferences, session: partition}});
const window = signIn;
const contents = window.webContents;
contents.setWindowOpenHandler(() => ({action: 'deny'}));
const checkNavigation = (event) => {
if (!officialOrigins.has(new URL(event.url).origin)) event.preventDefault();
};
contents.on('will-navigate', checkNavigation);
contents.on('will-redirect', checkNavigation);
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
contents.setUserAgent(partition.getUserAgent() + ' BBL-Slicer/v' + pairing.version +
' (' + theme + ') BBL-Language/' + app.getLocale().split('-')[0]);
window.on('closed', () => {
signIn = null;
if (!sending) pairing = null;
void partition.clearStorageData().catch(() => {});
});
return window.loadURL(officialSignIn);
}
ipcMain.handle('pairing:open', async (event, value) => {
if (!setup || event.senderFrame !== setup.webContents.mainFrame || signIn || sending)
return 'Close the current sign-in before starting another one.';
try {
pairing = parseLink(value);
} catch (error) {
return error.message;
}
const result = await dialog.showMessageBox(setup, {
type: 'question', title: 'Confirm Web Slicer server',
message: 'Send the Bambu sign-in to this Web Slicer?',
detail: pairing.origin, buttons: ['Cancel', 'Continue'], defaultId: 0, cancelId: 0
});
if (result.response !== 1) {pairing = null;return '';}
try {
await openSignIn();
return 'Complete sign-in in the Bambu Lab window.';
} catch {
signIn?.close();
pairing = null;
return 'Could not open the Bambu Lab sign-in page.';
}
});
ipcMain.on('pairing:result', async (event, message) => {
const frame = event.senderFrame;
if (!signIn || frame !== signIn.webContents.mainFrame || !frame ||
!officialOrigins.has(new URL(frame.url).origin) || !pairing || sending ||
typeof message !== 'string' || message.length > 65536) return;
let body;
try {
const {command, data} = JSON.parse(message);
if (command === 'user_ticket_login' && /^[A-Za-z0-9]{4,64}$/.test(data?.ticket ?? '')) body = {ticket: data.ticket};
if (command === 'user_login' && data && typeof data === 'object' && !Array.isArray(data)) body = {session: data};
} catch {return;}
if (!body) return;
sending = true;
const {endpoint, code} = pairing;
let accepted = false;
try {
const response = await fetch(endpoint, {
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(60000),
headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + code},
body: JSON.stringify(body)
});
accepted = response.status === 204;
} catch {/* Report a generic error without exposing credentials. */}
signIn?.close();
pairing = null;
sending = false;
if (setup && !setup.isDestroyed()) {
await dialog.showMessageBox(setup, {
type: accepted ? 'info' : 'error',
message: accepted ? 'Bambu Lab account linked' : 'Could not link the Bambu Lab account',
detail: accepted ? 'You can return to Web Slicer now.' : 'Create a new pairing link in Web Slicer and try again.'
});
}
});
app.whenReady().then(() => {
setup = new BrowserWindow({title: 'Web Slicer Bambu Login', width: 620, height: 360, webPreferences: preferences});
setup.webContents.setWindowOpenHandler(() => ({action: 'deny'}));
setup.webContents.on('will-navigate', event => event.preventDefault());
setup.on('closed', () => {setup = null;app.quit();});
return setup.loadFile(path.join(__dirname, 'index.html'));
});
app.on('window-all-closed', () => app.quit());
+728
View File
@@ -0,0 +1,728 @@
{
"name": "web-slicer-bambu-login",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "web-slicer-bambu-login",
"version": "0.1.0",
"devDependencies": {
"@electron/packager": "20.3.0",
"electron": "45.4.1"
}
},
"node_modules/@electron-internal/extract-zip": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.8.tgz",
"integrity": "sha512-8iajeLFbzNwM0m3AsQZSZgYREWglAImyGvvFSWU34FgMW8sHlzdwj9QKvv9dgN7jMP591EFUF/sLOC3Jl9YIjQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/@electron/asar": {
"version": "4.3.2",
"resolved": "https://registry.npmjs.org/@electron/asar/-/asar-4.3.2.tgz",
"integrity": "sha512-2nwyO3OgmLgkYQe6TzB8FmyrBKGgmXzSO51ozoG2BpHOLPTPdQpBt/zD0MdPkhQr4UqVgw3u09y4uYxgZKhmtg==",
"dev": true,
"license": "MIT",
"dependencies": {
"glob": "^14.0.2",
"minimatch": "^11.0.1"
},
"bin": {
"asar": "bin/asar.mjs"
},
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/@electron/get": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
"integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
"dev": true,
"license": "MIT",
"dependencies": {
"debug": "^4.1.1",
"env-paths": "^3.0.0",
"graceful-fs": "^4.2.11",
"progress": "^2.0.3",
"semver": "^7.6.3",
"sumchecker": "^3.0.1"
},
"engines": {
"node": ">=22.12.0"
},
"optionalDependencies": {
"undici": "^7.24.4"
}
},
"node_modules/@electron/notarize": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-3.1.2.tgz",
"integrity": "sha512-S/EH6W/GTe3XiD4oYHW+6xuUWZWjc9F5gayMrNdmRLv7qG9KRYmYE26+RDgC1hYUZVY3qLpa1VftxuL+sL5VQg==",
"dev": true,
"license": "MIT",
"dependencies": {
"debug": "^4.4.0",
"promise-retry": "^2.0.1"
},
"engines": {
"node": ">= 22.12.0"
}
},
"node_modules/@electron/osx-sign": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-2.7.2.tgz",
"integrity": "sha512-BD5ZyKDzzC1PLzWQCl1nw+X2/ErRCJGEIPwtjfOnCH+8KRLfBe/Vr9khUuEJC5bbrVACl8uO2Q2O/UqOzrcFgw==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"debug": "^4.3.4",
"isbinaryfile": "^4.0.8",
"plist": "^3.0.5",
"semver": "^7.7.1"
},
"bin": {
"electron-osx-flat": "bin/electron-osx-flat.mjs",
"electron-osx-sign": "bin/electron-osx-sign.mjs"
},
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/@electron/packager": {
"version": "20.3.0",
"resolved": "https://registry.npmjs.org/@electron/packager/-/packager-20.3.0.tgz",
"integrity": "sha512-3MvgJgy6YJ5ti0oGGBKrWKdYwpTaoRrhranMDgHSQ6i5t56yZV9IRDyoXTuqBp97LiKqnZeAMe2wTcF/9+fP5g==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"@electron-internal/extract-zip": "^1.0.1",
"@electron/asar": "^4.0.1",
"@electron/get": "^5.0.0",
"@electron/notarize": "^3.1.0",
"@electron/osx-sign": "^2.2.0",
"@electron/universal": "^3.0.1",
"@electron/windows-sign": "^2.0.2",
"@malept/cross-spawn-promise": "^2.0.0",
"debug": "^4.4.1",
"filenamify": "^6.0.0",
"galactus": "^2.0.2",
"graceful-fs": "^4.2.11",
"junk": "^4.0.1",
"plist": "^3.1.0",
"resedit": "^2.0.3",
"semver": "^7.7.2",
"yargs-parser": "^22.0.0"
},
"bin": {
"electron-packager": "bin/electron-packager.mjs"
},
"engines": {
"node": ">= 22.12.0"
},
"funding": {
"url": "https://github.com/electron/packager?sponsor=1"
}
},
"node_modules/@electron/universal": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@electron/universal/-/universal-3.0.6.tgz",
"integrity": "sha512-MonS1kfkZdSEkLZI0pdR/TCx8ecxwRSFm7sORfwIkDI9UaIbHnk4Mgeqq+Ob9qDQRV8LZ9+hHCmimpA9BRcNxw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@electron/asar": "^4.0.0",
"debug": "^4.3.1",
"plist": "^3.1.0"
},
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/@electron/windows-sign": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@electron/windows-sign/-/windows-sign-2.1.0.tgz",
"integrity": "sha512-hyRE175pWNxU3R0k7B7Zwm4KpSgK/Ql+7yqUPRfnYc9K06uVPJDLvXH6oXpl/RAKbLu0Y114xuH6BdjDhF/pKA==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"debug": "^4.3.4",
"graceful-fs": "^4.2.11",
"postject": "^1.0.0-alpha.6"
},
"bin": {
"electron-windows-sign": "bin/electron-windows-sign.mjs"
},
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/@isaacs/nonrecursive-glob-match": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
"integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
"dev": true,
"license": "BlueOak-1.0.0"
},
"node_modules/@malept/cross-spawn-promise": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz",
"integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==",
"dev": true,
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/malept"
},
{
"type": "tidelift",
"url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund"
}
],
"license": "Apache-2.0",
"dependencies": {
"cross-spawn": "^7.0.1"
},
"engines": {
"node": ">= 12.13.0"
}
},
"node_modules/@types/node": {
"version": "24.19.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
"integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": ">=7.24.0 <7.24.7"
}
},
"node_modules/@xmldom/xmldom": {
"version": "0.9.12",
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz",
"integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.6"
}
},
"node_modules/balanced-match": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "18 || 20 || >=22"
}
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/brace-expansion": {
"version": "5.0.13",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz",
"integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
"node": "20 || >=22"
}
},
"node_modules/commander": {
"version": "9.5.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz",
"integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^12.20.0 || >=14"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
"which": "^2.0.1"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/electron": {
"version": "45.4.1",
"resolved": "https://registry.npmjs.org/electron/-/electron-45.4.1.tgz",
"integrity": "sha512-DjsJ/eQhovkjf1vYFFyh5GB8NMx+L5bdYaonvGOlWselg3DQ0fwIF0N/+2hrPsoS4whmmNswh21ym/8dgt1y5Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"@electron-internal/extract-zip": "^1.0.1",
"@electron/get": "^5.0.0",
"@types/node": "^24.9.0"
},
"bin": {
"electron": "cli.js",
"install-electron": "install.js"
},
"engines": {
"node": ">= 22.12.0"
}
},
"node_modules/env-paths": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
"integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/err-code": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz",
"integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==",
"dev": true,
"license": "MIT"
},
"node_modules/filename-reserved-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/filename-reserved-regex/-/filename-reserved-regex-3.0.0.tgz",
"integrity": "sha512-hn4cQfU6GOT/7cFHXBqeBg2TbrMBgdD0kcjLhvSQYYwm3s4B6cjvBfb7nBALJLAXqmU5xajSa7X2NnUud/VCdw==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/filenamify": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/filenamify/-/filenamify-6.0.0.tgz",
"integrity": "sha512-vqIlNogKeyD3yzrm0yhRMQg8hOVwYcYRfjEoODd49iCprMn4HL85gK3HcykQE53EPIpX3HcAbGA5ELQv216dAQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"filename-reserved-regex": "^3.0.0"
},
"engines": {
"node": ">=16"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/flora-colossus": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/flora-colossus/-/flora-colossus-3.0.2.tgz",
"integrity": "sha512-Jk78K/Tzt6saxQPGChlJw69xuFGpWyTSAS8EdU0h/FyXwD2K46yNOXmo6nRHcZ9ooekyBAzMkwmiGNt7wOC5zg==",
"dev": true,
"license": "MIT",
"dependencies": {
"debug": "^4.4.1"
},
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/galactus": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/galactus/-/galactus-2.0.2.tgz",
"integrity": "sha512-HmKyTFGomdAchz4umx8MwBnrnfFmdpwiTyGA4ZOF7rya2Lmgbc9qate4yweInL+0gUBVImhaz12SBGpW3SY4Yg==",
"dev": true,
"license": "MIT",
"dependencies": {
"debug": "^4.4.1",
"flora-colossus": "^3.0.2"
},
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/glob": {
"version": "14.0.6",
"resolved": "https://registry.npmjs.org/glob/-/glob-14.0.6.tgz",
"integrity": "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"minimatch": "^11.0.5",
"minipass": "^7.1.3",
"path-scurry": "^3.0.0"
},
"engines": {
"node": "18 || 20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/graceful-fs": {
"version": "4.2.12",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz",
"integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==",
"dev": true,
"license": "BlueOak-1.0.0"
},
"node_modules/isbinaryfile": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz",
"integrity": "sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 8.0.0"
},
"funding": {
"url": "https://github.com/sponsors/gjtorikian/"
}
},
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"dev": true,
"license": "ISC"
},
"node_modules/junk": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/junk/-/junk-4.0.1.tgz",
"integrity": "sha512-Qush0uP+G8ZScpGMZvHUiRfI0YBWuB3gVBYlI0v0vvOJt5FLicco+IkP0a50LqTTQhmts/m6tP5SWE+USyIvcQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12.20"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/lru-cache": {
"version": "11.5.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
"integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
"dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
}
},
"node_modules/minimatch": {
"version": "11.0.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
"integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/nonrecursive-glob-match": "^1.1.0",
"brace-expansion": "^5.0.12"
},
"engines": {
"node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/minipass": {
"version": "7.1.3",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
"integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
"dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=16 || 14 >=14.17"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true,
"license": "MIT"
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/path-scurry": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz",
"integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"lru-cache": "^11.0.0",
"minipass": "^7.1.2"
},
"engines": {
"node": "18 || 20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/pe-library": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pe-library/-/pe-library-1.0.1.tgz",
"integrity": "sha512-nh39Mo1eGWmZS7y+mK/dQIqg7S1lp38DpRxkyoHf0ZcUs/HDc+yyTjuOtTvSMZHmfSLuSQaX945u05Y2Q6UWZg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14",
"npm": ">=7"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/jet2jet"
}
},
"node_modules/plist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz",
"integrity": "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@xmldom/xmldom": "^0.9.10",
"base64-js": "^1.5.1",
"xmlbuilder": "^15.1.1"
},
"engines": {
"node": ">=10.4.0"
}
},
"node_modules/postject": {
"version": "1.0.0-alpha.6",
"resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz",
"integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==",
"dev": true,
"license": "MIT",
"dependencies": {
"commander": "^9.4.0"
},
"bin": {
"postject": "dist/cli.js"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/progress": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
"integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/promise-retry": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz",
"integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==",
"dev": true,
"license": "MIT",
"dependencies": {
"err-code": "^2.0.2",
"retry": "^0.12.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/resedit": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/resedit/-/resedit-2.0.3.tgz",
"integrity": "sha512-oTeemxwoMuxxTYxXUwjkrOPfngTQehlv0/HoYFNkB4uzsP1Un1A9nI8JQKGOFkxpqkC7qkMs0lUsGrvUlbLNUA==",
"dev": true,
"license": "MIT",
"dependencies": {
"pe-library": "^1.0.1"
},
"engines": {
"node": ">=14",
"npm": ">=7"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/jet2jet"
}
},
"node_modules/retry": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
"integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/semver": {
"version": "7.8.6",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
"integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/shebang-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/sumchecker": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
"integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"debug": "^4.1.0"
},
"engines": {
"node": ">= 8.0"
}
},
"node_modules/undici": {
"version": "7.30.2",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz",
"integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==",
"dev": true,
"license": "MIT",
"optional": true,
"engines": {
"node": ">=20.18.1"
}
},
"node_modules/undici-types": {
"version": "7.24.6",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
"dev": true,
"license": "MIT"
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
},
"bin": {
"node-which": "bin/node-which"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/xmlbuilder": {
"version": "15.1.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
"integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8.0"
}
},
"node_modules/yargs-parser": {
"version": "22.0.0",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",
"integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",
"dev": true,
"license": "ISC",
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=23"
}
}
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "web-slicer-bambu-login",
"productName": "Web Slicer Bambu Login",
"version": "0.1.0",
"private": true,
"main": "main.cjs",
"scripts": {
"start": "electron .",
"package": "electron-packager . WebSlicerBambuLogin --out=dist --asar"
},
"devDependencies": {
"@electron/packager": "20.3.0",
"electron": "45.4.1"
}
}
+16
View File
@@ -0,0 +1,16 @@
const {contextBridge, ipcRenderer} = require('electron');
if (process.isMainFrame) {
if (location.protocol === 'file:') {
contextBridge.exposeInMainWorld('helper', {
open: link => ipcRenderer.invoke('pairing:open', link)
});
} else if (location.origin === 'https://bambulab.com' || location.origin === 'https://www.bambulab.com') {
contextBridge.exposeInMainWorld('wx', {
postMessage: message => {
if (typeof message === 'string' && message.length <= 65536)
ipcRenderer.send('pairing:result', message);
}
});
}
}
+16
View File
@@ -0,0 +1,16 @@
const form = document.querySelector('form');
const field = document.querySelector('#link');
const status = document.querySelector('#status');
const button = form.querySelector('button');
form.addEventListener('submit', async event => {
event.preventDefault();
button.disabled = true;
try {
status.textContent = await window.helper.open(field.value);
if (status.textContent.startsWith('Complete sign-in')) field.value = '';
} catch {
status.textContent = 'Could not start sign-in. Make sure the helper is up to date.';
} finally {
button.disabled = false;
}
});
+6
View File
@@ -0,0 +1,6 @@
:root{color-scheme:light dark;font:16px system-ui}
body{max-width:520px;margin:28px auto;padding:0 22px}
h1{font-size:1.45rem;margin-bottom:24px}
form{display:grid;gap:12px}
input,button{font:inherit;padding:9px 12px}
button{justify-self:start}
+12
View File
@@ -7,6 +7,18 @@ diameter, density and notes. It has no physical-spool inventory, remaining-mass
accounting, batch tracking or storage location. These are outside the product
model; an optional inventory integration can reference the product separately.
A library manager can start a filament product from a system or imported
filament preset. The picker supports search, material and manufacturer filters,
and groups printer-specific variants by filament. The preset fills the draft with product metadata, including
material, manufacturer, color, diameter and density. Saving creates the
independent product. Printer availability and compatible slicing profiles
can be added separately for each printer and nozzle.
Bambu AMS observations report slot metadata and assignment identity. To use a
slot in a project, assign and confirm the product in Device and select its
compatible slicing profile. The project records the slot and the confirmed
assignment revision so that dispatch can check it against the live printer.
## Ownership and visibility
Products belong to explicit filament libraries, stored in the instance database.
+7
View File
@@ -324,6 +324,13 @@ known limitations. Users need only `compose.yaml` and `.env`. Do not create a
Gitea release or upload release attachments. Do not advertise images before
the registry and startup of the published images have been checked.
The web image serves portable Linux and Windows Bambu desktop helper archives
under `/bambu-login/`. They are built from the helper source in the same
revision. Bambu Cloud itself requires separately supplied native host and
networking plugin binaries configured through
`ORCA_BAMBU_CLOUD_HOST` and `ORCA_BAMBU_CLOUD_PLUGIN`. The standard app image
does not include those binaries.
## Public static demo
The optional `demo` image uses the same GUI build and release tag. It contains
+40
View File
@@ -48,6 +48,46 @@ are intentional web-product decisions. They must not be overwritten merely to
match upstream desktop behavior. This requirements record describes the intended
redesign, not the currently implemented API.
## Surfacing new settings and GUI options
This fork replaces OrcaSlicer's wxWidgets desktop GUI with a React web client.
A merge that only resolves C++ and builds is **not finished**: a new upstream
option must actually appear in our GUI. A merge that leaves our GUI untouched is
incomplete, not a success — every user-facing upstream addition is surfaced in
the web client or recorded as a deliberate, explained deferral, never silently
dropped.
How settings reach the web client:
- Field definitions, types, enum values, defaults and visibility come from the
native **schema** (the worker's `schema` operation, generated from
`PrintConfig.cpp`). A new `ConfigOptionDef` flows through automatically.
- **Placement** (which page and group a key shows under) comes from
`web/frontend/src/generated/setting-layout.json`, generated by
`web/scripts/build-setting-layout.mjs`, which parses the page/group
registration in `src/slic3r/GUI/Tab.cpp` (`TabPrint::build`,
`TabFilament::build`, `TabPrinter::build_fff`, …). A key with no layout entry
is not placed on any page, so it never renders even though the schema has it.
After any upstream merge that touches `PrintConfig.cpp` or `Tab.cpp`:
1. Regenerate the layout: `node web/scripts/build-setting-layout.mjs` and commit
the result. The generator throws if its extraction looks incomplete; the
count line it prints should grow by roughly the number of options upstream
added.
2. Open process, filament and printer settings in the web client and confirm the
new options actually appear, with sane labels, units and enum choices.
`web/frontend/tests/setting-layout.test.mjs` guards the extraction.
3. Options upstream exposes through custom wxWidgets widgets, a new page, or a
registration pattern the extractor does not match are **not** captured
automatically. Extend the extractor or add the control to the web client so
the option is reachable; if it genuinely does not apply to the web product,
record that decision rather than leaving it missing.
4. The same applies beyond the settings tabs: a new upstream GUI capability that
users would rely on (a calibration, a device action, a project control) is
reimplemented in the web client where it matters, not assumed present because
the C++ merged.
## Validation boundaries
Check headless and desktop compilation, settings normalization, 3MF round trips,
+46
View File
@@ -14,6 +14,7 @@
// {"id":N,"op":"ping"|"status"|"logout"}
// {"id":N,"op":"login_ticket","ticket":"..."}
// {"id":N,"op":"login_session","session":{...}}
// {"id":N,"op":"user_presets"} account preset download (REST)
// {"id":N,"op":"devices"} bound printers (REST)
// {"id":N,"op":"connect"} cloud MQTT session
// {"id":N,"op":"subscribe","dev_ids":[...]}
@@ -27,10 +28,12 @@
#include <atomic>
#include <cctype>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <stdexcept>
@@ -68,6 +71,10 @@ using subscribe_fn = int (*)(void*, std::vector<std::string>);
using send_fn = int (*)(void*, std::string, std::string, int, int);
using on_message_fn = int (*)(void*, BBL::OnMessageFn);
using on_server_fn = int (*)(void*, BBL::OnServerConnectedFn);
using user_presets = std::map<std::string, std::map<std::string, std::string>>;
using get_setting_list_fn = int (*)(void*, std::string, BBL::ProgressFn, BBL::WasCancelledFn);
using put_setting_fn = int (*)(void*, std::string, std::string, std::map<std::string, std::string>*, unsigned int*);
using get_user_presets_fn = int (*)(void*, user_presets*);
using start_print_fn = int (*)(void*, BBL::PrintParams, BBL::OnUpdateStatusFn, BBL::WasCancelledFn, BBL::OnWaitFn);
std::mutex g_out;
@@ -101,6 +108,9 @@ struct Plugin {
on_message_fn set_on_message = nullptr;
on_server_fn set_on_server_connected = nullptr;
start_print_fn start_print = nullptr;
get_user_presets_fn get_user_presets = nullptr;
get_setting_list_fn get_setting_list = nullptr;
put_setting_fn put_setting = nullptr;
std::thread print_thread;
std::atomic<bool> printing{false};
@@ -168,6 +178,11 @@ bool load_plugin(const std::string& path, const std::string& data_dir, const std
&& resolve(p.lib, "bambu_network_set_on_server_connected_fn", p.set_on_server_connected)
&& resolve(p.lib, "bambu_network_start_print", p.start_print);
if (!ok) return false;
if (cloud) {
p.get_user_presets = reinterpret_cast<get_user_presets_fn>(dlsym(p.lib, "bambu_network_get_user_presets"));
p.get_setting_list = reinterpret_cast<get_setting_list_fn>(dlsym(p.lib, "bambu_network_get_setting_list"));
p.put_setting = reinterpret_cast<put_setting_fn>(dlsym(p.lib, "bambu_network_put_setting"));
}
// Private directories: the plugin keeps its session store under config/.
const std::string config = data_dir + "/config";
const std::string logs = data_dir + "/logs";
@@ -368,6 +383,37 @@ json handle(Plugin& p, const json& req) {
if (rc != 0) throw std::runtime_error("logout failed");
return status(p);
}
if (op == "update_user_preset") {
if (!p.put_setting) throw std::runtime_error("This Bambu networking plugin does not support preset updates");
if (!p.is_user_login(p.agent) || p.get_user_id(p.agent) != req.at("account").get<std::string>())
throw std::runtime_error("The signed-in Bambu Lab account changed");
auto values = req.at("content").get<std::map<std::string, std::string>>();
unsigned int http_code = 0;
const int result = p.put_setting(p.agent, req.at("setting_id").get<std::string>(),
req.at("name").get<std::string>(), &values, &http_code);
if (result != 0)
throw std::runtime_error("Bambu preset update failed (code " + std::to_string(result) + ")");
return {{"updated", true}};
}
if (op == "user_presets") {
if (!p.get_user_presets || !p.get_setting_list) throw std::runtime_error("This Bambu networking plugin does not support preset downloads");
if (!p.is_user_login(p.agent)) throw std::runtime_error("Sign in to Bambu Lab to download presets");
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(35);
const int fetched = p.get_setting_list(p.agent, req.at("bundle_version").get<std::string>(), {}, [deadline] {
return std::chrono::steady_clock::now() >= deadline;
});
user_presets values;
const int drained = p.get_user_presets(p.agent, &values);
if (fetched != 0 || drained != 0)
throw std::runtime_error("Bambu preset download failed (code " + std::to_string(fetched != 0 ? fetched : drained) + ")");
if (!req.value("include_identity", false)) {
for (auto& entry : values) {
entry.second.erase("user_id");
entry.second.erase("setting_id");
}
}
return {{"presets", values}, {"account", p.get_user_id(p.agent)}};
}
if (op == "devices") return devices(p);
if (op == "connect") {
require_cloud(p);
+30
View File
@@ -958,3 +958,33 @@ and played through mpegts.js (magicxqq / xqq and contributors, Apache-2.0), whos
original notices appear in the browser component credits. No video decoding,
ffmpeg process or persistent media cache is added to the server. Stop or leave
the panel to close the stream.
### Opening a model from another application
Send a multipart `file` to `POST /api/v1/imports/open-model` using the normal
Web Slicer session and CSRF header. Accepted formats are 3MF, STL, STEP and
STP, up to 512 MiB. The response is the durable import job. Its `Location`
header opens the Web Slicer UI, which follows the job and opens the resulting
project. API clients can poll `GET /api/v1/imports/{id}`.
The endpoint opens a new project. It uses the user's remembered printer or
their only visible printer. Clients can provide `machine_id` and, optionally,
`profile_id` in the query string. STL dimensions are kept, STEP uses native
tessellation defaults, and 3MF is opened as geometry with the destination
printer's settings. Optional rescaling and texture painting are skipped.
For a public model URL, link to the Web Slicer base URL with the fragment
`#open-model=<encoded-model-url>`. Add `&filename=<encoded-filename>` if the
download URL does not end in a supported extension. The browser downloads
the file without credentials. Cross-origin downloads require CORS on the model
host. The API never fetches model URLs.
Applications with private files can open a tab with
`#open-model-from=<encoded-sender-origin>&request=<32-hex-digit-request-id>`.
After the user has signed in, Web Slicer sends its opener a message with
`protocol: "web-slicer.open-model.v1"`, `type: "ready"`, and `request`.
The opener checks the window and origin and replies with the same protocol
and request, `type: "file"`, and a browser `File` in `file`. Web Slicer
replies with `accepted` after queuing the import, or `failed` if it cannot
queue it. Both sides address their messages to the exact target origin.
Keep the opener relationship for this flow.
+7 -3
View File
@@ -16,7 +16,7 @@ COMMON_READS = {
'/dispatches', '/profiles', '/user-profiles', '/workspace', '/accounts', '/health',
'/capabilities', '/settings/schema', '/settings/gcode/placeholders', '/preferences/imports',
'/printer/types', '/printer/device-agents', '/printer-library/thumbnail', '/upstream-release',
'/emboss/fonts', '/emboss/styles', '/machine-wizard/catalog',
'/emboss/fonts', '/emboss/styles', '/machine-wizard/catalog', '/filament-product-template',
}
PROJECT_READS = {
'/open', '/selection-state', '/validation', '/measure', '/gcode/check',
@@ -369,7 +369,7 @@ class AccessPolicy:
return
user = getattr(request.state, 'local_user', None)
path = route.path.removeprefix('/api/v1')
if path in {'/auth/login', '/auth/me', '/liveness'}:
if path in {'/auth/login', '/auth/me', '/liveness'} or (path == '/bambu-cloud/desktop-login/redeem' and request.method == 'POST'):
return
if not user:
raise HTTPException(401, 'Sign in to continue')
@@ -377,7 +377,9 @@ class AccessPolicy:
return # Catalogue services check current actor, ownership and printer grants transactionally.
if path.startswith('/print-requests') or '/print-requests' in path:
return # The service checks both resources and the frozen submission in its transaction.
if user['admin'] or path in {'/auth/logout', '/auth/password'}:
if user['admin'] or path in {'/auth/logout', '/auth/password'} or path == '/bambu-cloud' or path.startswith('/bambu-cloud/'):
# Bambu cloud credentials and direct cloud job receipts are scoped to
# the current user. Cloud printing also checks the project's grant.
return
params, method = request.path_params, request.method
self.references(dict(request.query_params), user)
@@ -435,6 +437,8 @@ class AccessPolicy:
job = self.app.state.operations.get(params['job_id'])
self.reference_project(job['payload']['project_id'], user, edit=method not in READ and not path.endswith('/copy'))
return
if path == '/imports/open-model' and method == 'POST':
return # The handler selects only printers visible to the current actor.
if path == '/imports' and method == 'POST':
self.reference_project(body.get('project_id'), user, edit=True)
selection = body.get('machine')
+10 -2
View File
@@ -854,6 +854,7 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
asyncio.create_task(refresh_orca_cloud(app.state.orca_cloud)),
asyncio.create_task(app.state.orca_profile_automatic.run()),
asyncio.create_task(app.state.background_slicing.run())]
preset_sync_task = asyncio.create_task(app.state.bambu_preset_sync.run()) if app.state.bambu_preset_sync else None
try:
yield
finally:
@@ -872,8 +873,12 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
await app.state.simplyprint_oauth.close()
await app.state.orca_profile_automatic.close()
await app.state.orca_cloud.close()
if preset_sync_task:
preset_sync_task.cancel()
await asyncio.gather(preset_sync_task, return_exceptions=True)
if getattr(app.state, 'bambu_cloud_relay', None) is not None:
await asyncio.to_thread(app.state.bambu_cloud_relay.close)
await app.state.close_bambu_user_hosts()
if getattr(app.state, 'bambu_cloud', None) is not None:
await asyncio.to_thread(app.state.bambu_cloud.close)
await app.state.printeros_logins.close()
@@ -911,8 +916,6 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
install_printer_renders_api(app)
install_printer_history_api(app)
install_printer_commands_api(app, store)
from .bambu_cloud import install_bambu_cloud_api
install_bambu_cloud_api(app, store)
app.state.job_artifacts = job_artifacts
app.state.maintenance = maintenance
app.state.post_processing = post_processing
@@ -1130,6 +1133,9 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
except ValueError as error:
raise HTTPException(422, str(error)) from error
value['revision'] = body.revision
if value.get('bambu_transport') == 'cloud' and (user := app.state.access.current_user()):
value['_bambu_account_owner'] = (app.state.access.machine_capabilities(identity)['owner_id']
if identity else user['id'])
if value['type'] == 'plugin':
result = await plugin_printers.test_draft(value)
else:
@@ -2646,6 +2652,8 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
auth = install_auth_api(app, store)
from .access import install_access_api
install_access_api(app, store, auth)
from .bambu_cloud import install_bambu_cloud_api
install_bambu_cloud_api(app, store)
from .filament_products import install_filament_product_api
install_filament_product_api(app, store)
from .print_requests import PrintRequests, install_print_request_api
+5 -4
View File
@@ -53,14 +53,15 @@ class LocalAuthentication:
session_hash = digest(token) if 40 <= len(token) <= 64 else ''
user = await asyncio.to_thread(self.auth.session, session_hash, touch=True) if session_hash else None
scope.setdefault('state', {}).update(local_user=user, local_session=session_hash)
public = path in {PREFIX + '/me', PREFIX + '/login'}
desktop_redeem = method == 'POST' and path == '/api/v1/bambu-cloud/desktop-login/redeem'
public = desktop_redeem or path in {PREFIX + '/me', PREFIX + '/login'}
if path == PREFIX + '/login' and self.auth.secure:
origin = request.headers.get('origin')
if origin and not origin.startswith('https://'):
return await reject(400, 'HTTPS is required for sign in')
if self.auth.required and not user and not public:
return await reject(401, 'Sign in to continue', {'X-Orca-Auth-Required': '1'})
if method not in SAFE and (self.auth.required or local_mutation or path.startswith('/api/v1/admin/')):
if not desktop_redeem and method not in SAFE and (self.auth.required or local_mutation or path.startswith('/api/v1/admin/')):
origin = request.headers.get('origin')
if origin and origin not in self.allowed_origins and origin != str(request.base_url).rstrip('/'):
return await reject(403, 'Foreign origin rejected')
@@ -79,7 +80,7 @@ class LocalAuthentication:
if self.auth.required and user and admin_path and not user['admin']:
return await reject(403, 'Administrator access is required')
# Bound the complete auth payload before FastAPI/Pydantic decode it.
if method not in SAFE and (local_mutation or path.startswith('/api/v1/admin/')):
if desktop_redeem or method not in SAFE and (local_mutation or path.startswith('/api/v1/admin/')):
if request.headers.get('content-type', '').split(';')[0].lower() != 'application/json' and path != PREFIX + '/logout':
return await reject(415, 'Use application/json')
body = bytearray()
@@ -90,7 +91,7 @@ class LocalAuthentication:
if message['type'] == 'http.disconnect':
return
body.extend(message.get('body', b''))
if len(body) > 8192:
if len(body) > (72 * 1024 if desktop_redeem else 8192):
return await reject(413, 'Authentication request is too large')
if not message.get('more_body'):
break
+183 -31
View File
@@ -3,11 +3,11 @@
Drives the native orca-bambu-cloud host (src/headless/BambuCloudHost.cpp), which
loads open-bamboo-networking. Available only when both are configured through
ORCA_BAMBU_CLOUD_HOST and ORCA_BAMBU_CLOUD_PLUGIN (the cloud sideload build);
otherwise the API reports it as unavailable and starts nothing. One account per
instance, so the routes fall under the administrator default in access_control.
otherwise the API reports it as unavailable and starts nothing. Local account
mode has one Bambu session per user. Standalone mode keeps one device session.
A sign-in WebView (the Android app's, mirroring upstream OrcaSlicer's `wx`
bridge) captures what the Bambu page hands over and posts it here: either a
A sign-in WebView in the Android app or desktop helper captures the result
provided by the Bambu page and posts it here: either a
short ticket or an already-complete session. Neither is logged or returned.
"""
import asyncio
@@ -16,6 +16,7 @@ import json
import os
from pathlib import Path as FilePath
import queue
import re
import secrets
import socket
import socketserver
@@ -25,7 +26,7 @@ import time
from typing import Annotated
from fastapi import HTTPException, Path
from fastapi import HTTPException, Path, Request
from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validator
REPLY_TIMEOUT = 45 # A ticket exchange makes two HTTPS calls to Bambu.
@@ -54,7 +55,8 @@ class BambuLogin(BaseModel):
# keeps the same running merge of incremental pushes).
# Cloud device list model codes (Bambu printer model ids, as in Studio's machine profiles).
MODEL_NAMES = {'BL-P001': 'X1 Carbon', 'BL-P002': 'X1', 'C13': 'X1E', 'C11': 'P1P', 'C12': 'P1S',
'N1': 'A1 mini', 'N2S': 'A1'}
'N1': 'A1 mini', 'N2S': 'A1', 'N7': 'P2S', 'N9': 'A2L', 'N6': 'X2D',
'O1C2': 'H2C', 'O1E': 'H2D Pro', 'O1D': 'H2D', 'O1S': 'H2S'}
STATUS_FIELDS = ('gcode_state', 'mc_percent', 'mc_remaining_time', 'layer_num', 'total_layer_num',
'subtask_name', 'nozzle_temper', 'nozzle_target_temper', 'bed_temper', 'bed_target_temper',
'print_error', 'wifi_signal')
@@ -193,7 +195,15 @@ class BambuCloudHost:
raise RuntimeError('Bambu cloud host exited')
if not reply.get('ok'):
raise ValueError(reply.get('error') or 'Bambu cloud request failed')
return reply['result']
result = reply['result']
if op in {'login_ticket', 'login_session', 'logout'}:
with self.state_lock:
self.devices.clear()
self.printers.clear()
self.jobs.clear()
self.pushall_sent.clear()
self.server_connected = bool(result.get('cloud_connected'))
return result
def printer_status(self, dev_id):
with self.state_lock:
@@ -349,11 +359,12 @@ class CloudRelay:
return
dev_id = hello.get('dev_id')
try:
identity = self._open(dev_id)
host = self.host(hello.get('owner')) if callable(self.host) else self.host
identity = self._open(dev_id, host)
except (ValueError, RuntimeError, TimeoutError) as error:
send({'ok': False, 'error': str(error) or 'Bambu cloud is unavailable'})
return
listener = self.host.listen(dev_id)
listener = host.listen(dev_id)
closed = threading.Event()
def forward():
@@ -378,13 +389,13 @@ class CloudRelay:
if (payload.get('pushing') or {}).get('command') == 'pushall':
# The merged report is what a fresh pushall would return; ask the
# printer again only now and then.
forwarded = self.host.pushall(dev_id)
cached = self.host.full_report(dev_id)
forwarded = host.pushall(dev_id)
cached = host.full_report(dev_id)
send({'id': ident, 'sent': True})
if cached is not None and not forwarded:
send({'message': {'print': cached}})
else:
self.host.call('send', dev_id=dev_id, payload=payload)
host.call('send', dev_id=dev_id, payload=payload)
send({'id': ident, 'sent': True})
except (ValueError, RuntimeError, TimeoutError) as error:
send({'id': ident, 'error': str(error) or 'Bambu cloud send failed'})
@@ -392,7 +403,7 @@ class CloudRelay:
pass
finally:
closed.set()
self.host.unlisten(dev_id, listener)
host.unlisten(dev_id, listener)
@staticmethod
def _line(reader):
@@ -404,15 +415,16 @@ class CloudRelay:
except ValueError:
return None
def _open(self, dev_id):
def _open(self, dev_id, host=None):
host = host or self.host
if not isinstance(dev_id, str) or not dev_id.isalnum() or len(dev_id) > 64:
raise ValueError('Invalid Bambu printer id')
self.host.ensure_connected()
if dev_id not in self.host.devices:
self.host.device_list() # also subscribes the account's printers
if dev_id not in self.host.devices:
host.ensure_connected()
if dev_id not in host.devices:
host.device_list() # also subscribes the account's printers
if dev_id not in host.devices:
raise ValueError('This printer is not bound to the signed-in Bambu Lab account')
return self.host.lan_identity(dev_id)
return host.lan_identity(dev_id)
def configured_host(data_root):
@@ -425,16 +437,53 @@ def configured_host(data_root):
def install_bambu_cloud_api(app, store):
managed = app.state.auth.required
app.state.bambu_cloud = configured_host(store.root)
app.state.bambu_cloud_relay = None
if app.state.bambu_cloud is not None:
hosts = {}
hosts_lock = threading.Lock()
def user_host(owner):
if not isinstance(owner, str) or not re.fullmatch(r'[a-f0-9]{32}', owner):
raise ValueError('Sign in to reach this Bambu Lab account')
try:
user = app.state.access.account(owner)
except (KeyError, HTTPException):
raise ValueError('The Bambu Lab account owner is unavailable') from None
if user['disabled']:
raise ValueError('The Bambu Lab account owner is unavailable')
with hosts_lock:
if owner not in hosts:
host = configured_host(store.root / 'accounts' / owner)
if host is None:
raise ValueError('Bambu Lab cloud is not available')
normalize_stored_crl(host)
hosts[owner] = host
return hosts[owner]
def account_host():
if not managed:
return app.state.bambu_cloud
if app.state.bambu_cloud is None:
return None
user = app.state.access.current_user()
if not user:
raise HTTPException(401, 'Sign in to access your Bambu Lab account')
return user_host(user['id'])
async def close_user_hosts():
await asyncio.gather(*(asyncio.to_thread(host.close) for host in list(hosts.values())))
app.state.close_bambu_user_hosts = close_user_hosts
app.state.bambu_account_host = account_host
if app.state.bambu_cloud is not None and not managed:
normalize_stored_crl(app.state.bambu_cloud) # repair a CRL saved before the concatenation fix
if app.state.bambu_cloud is not None and app.state.bambu_cloud.cloud:
app.state.bambu_cloud_relay = CloudRelay(app.state.bambu_cloud)
app.state.bambu_cloud_relay = CloudRelay(user_host if managed else app.state.bambu_cloud)
os.environ[RELAY_ENV] = app.state.bambu_cloud_relay.address # inherited by printer workers
async def run(op, **fields):
host = app.state.bambu_cloud
async def run(op, *, host=None, **fields):
host = host or account_host()
if host is None:
raise HTTPException(404, 'Bambu cloud is not available in this build')
try:
@@ -446,25 +495,125 @@ def install_bambu_cloud_api(app, store):
except RuntimeError as error:
raise HTTPException(503, str(error)) from error
from .bambu_preset_sync import BambuPresetSync
sync = BambuPresetSync(store, app.state.worker, run) if app.state.bambu_cloud_relay and not managed else None
app.state.bambu_preset_sync = sync
class PresetSyncPreference(BaseModel):
enabled: bool
async def signed_in_account():
if sync is None:
raise HTTPException(404, 'Bambu Lab preset synchronization is unavailable')
state = await run('status')
if not state.get('logged_in') or not state.get('user_id'):
raise HTTPException(409, 'Sign in to Bambu Lab to synchronize presets')
return state['user_id']
@app.get('/api/v1/bambu-cloud/preset-sync')
async def preset_sync_state():
account = await signed_in_account()
return sync.state(account)
@app.put('/api/v1/bambu-cloud/preset-sync')
async def preset_sync_preference(body: PresetSyncPreference):
account = await signed_in_account()
sync.configure(account, body.enabled)
return sync.state(account)
@app.post('/api/v1/bambu-cloud/preset-sync')
async def preset_sync_request():
account = await signed_in_account()
if not sync.enabled(account):
raise HTTPException(409, 'Enable Bambu Lab preset synchronization first')
sync.wake.set()
return sync.state(account)
@app.get('/api/v1/bambu-cloud')
async def bambu_cloud_status():
host = app.state.bambu_cloud
host = account_host()
if host is None:
return {'available': False}
state = await run('status')
return {'available': True, 'plugin_version': host.plugin_version, **state}
return {'available': True, 'plugin_version': host.plugin_version, 'personal_account': managed, **state,
**({'preset_sync': sync.state(state['user_id'])} if sync and state.get('user_id') else {})}
async def login(body, host=None):
async def sign_in():
if body.ticket is not None:
return await run('login_ticket', host=host, ticket=body.ticket)
return await run('login_session', host=host, session=body.session)
if sync is None:
state = await sign_in()
else:
async with sync.lock:
state = await sign_in()
sync.wake.set()
if not state.get('logged_in'):
raise HTTPException(422, 'Bambu Lab did not accept this sign-in')
return {'available': True, 'personal_account': managed, **state}
desktop_codes = {}
@app.post('/api/v1/bambu-cloud/login')
async def bambu_cloud_login(body: BambuLogin):
if body.ticket is not None:
state = await run('login_ticket', ticket=body.ticket)
user = app.state.access.current_user()
if user:
desktop_codes.pop(user['id'], None)
return await login(body)
@app.post('/api/v1/bambu-cloud/desktop-login')
async def create_desktop_code(request: Request):
host = host_or_404()
user = request.state.local_user
if not user or not request.state.local_session:
raise HTTPException(403, 'Sign in to Web Slicer to use the desktop helper')
origin = request.headers.get('origin')
if not origin or not origin.startswith('https://'):
raise HTTPException(400, 'Use the HTTPS Web Slicer address to pair the desktop helper')
now = time.monotonic()
for identity, entry in list(desktop_codes.items()):
if entry[2] <= now:
desktop_codes.pop(identity, None)
token = secrets.token_urlsafe(32)
desktop_codes[user['id']] = (token, request.state.local_session, now + 600)
return {'code': token, 'expires_in': 600, 'plugin_version': host.plugin_version}
@app.delete('/api/v1/bambu-cloud/desktop-login', status_code=204)
async def cancel_desktop_code(request: Request):
user = request.state.local_user
entry = desktop_codes.get(user['id']) if user else None
if entry and entry[1] == request.state.local_session:
desktop_codes.pop(user['id'], None)
@app.post('/api/v1/bambu-cloud/desktop-login/redeem', status_code=204)
async def redeem_desktop_code(request: Request, body: BambuLogin):
supplied = request.headers.get('authorization', '').removeprefix('Bearer ')
if not request.headers.get('origin') and re.fullmatch(r'[A-Za-z0-9_-]{43}', supplied):
for identity, (token, session, expires) in desktop_codes.items():
if expires > time.monotonic() and hmac.compare_digest(supplied, token):
break
else:
raise HTTPException(403, 'The pairing code is invalid or expired')
else:
state = await run('login_session', session=body.session)
return {'available': True, **state}
raise HTTPException(403, 'The pairing code is invalid or expired')
desktop_codes.pop(identity, None)
user = await asyncio.to_thread(app.state.auth.session, session)
if not user or user['id'] != identity:
raise HTTPException(403, 'The Web Slicer session has ended')
await login(body, user_host(identity))
@app.post('/api/v1/bambu-cloud/logout')
async def bambu_cloud_logout():
return {'available': True, **await run('logout')}
user = app.state.access.current_user()
if user:
desktop_codes.pop(user['id'], None)
if sync is None:
state = await run('logout')
else:
async with sync.lock:
state = await run('logout')
return {'available': True, 'personal_account': managed, **state}
@app.get('/api/v1/bambu-cloud/slicer-key')
async def bambu_cloud_slicer_key():
@@ -486,7 +635,7 @@ def install_bambu_cloud_api(app, store):
return slicer_key_state(host)
def host_or_404():
host = app.state.bambu_cloud
host = account_host()
if host is None or not host.cloud:
raise HTTPException(404, 'Bambu cloud printers are not available in this build')
return host
@@ -528,6 +677,9 @@ def install_bambu_cloud_api(app, store):
job = store.job(body.job_id)
if job is None:
raise HTTPException(404, 'Unknown slicing job')
if user := app.state.access.current_user():
app.state.access.require('project', job['project_id'], user)
app.state.access.require_machine(store.job_machine(body.job_id), user, 'direct_print')
result = job.get('result') or {}
if job.get('status') != 'completed' or result.get('upload_format') != 'gcode_3mf':
raise HTTPException(409, 'Slice for a Bambu Lab printer first (the job has no printable .gcode.3mf)')
+9 -7
View File
@@ -51,7 +51,7 @@ def unavailable(error=None):
class RelayConnection:
"""Blocking client of the relay; MQTT payloads queue up while a publish waits."""
def __init__(self, dev_id, timeout):
def __init__(self, dev_id, timeout, owner=None):
port, token = relay_address()
self.timeout = timeout
self.ids = itertools.count(1)
@@ -62,7 +62,7 @@ class RelayConnection:
raise unavailable() from error
self.reader = self.socket.makefile('rb')
try:
self._write({'token': token, 'dev_id': dev_id})
self._write({'token': token, 'dev_id': dev_id, 'owner': owner})
hello = self._read(time.monotonic() + max(timeout, 30)) # first use may sign in and list devices
except (OSError, TimeoutError, ValueError) as error:
self.close()
@@ -145,10 +145,11 @@ class CloudMQTT:
class BambuCloudLink(BambuLAN):
def __init__(self, *, serial_number, timeout=12, printer_model='', **options):
def __init__(self, *, serial_number, timeout=12, printer_model='', account_owner=None, **options):
# Cloud round trips (phone -> Bambu -> printer -> Bambu -> phone) are slower than LAN.
super().__init__(f'http://{UNKNOWN_HOST}/', PLACEHOLDER_CODE, serial_number=serial_number,
timeout=max(timeout, 20), printer_model=printer_model, **options)
self.account_owner = account_owner
self.resolved = False
self._resolving = False
@@ -174,7 +175,7 @@ class BambuCloudLink(BambuLAN):
"""Point LAN-side features (camera, files) at the printer's reported address."""
if self.resolved and self._host != UNKNOWN_HOST: # an address may arrive after the first lookup
return self
relay = RelayConnection(self.serial_number, self.timeout)
relay = RelayConnection(self.serial_number, self.timeout, self.account_owner)
relay.close()
self._apply(relay.identity)
return self
@@ -190,7 +191,7 @@ class BambuCloudLink(BambuLAN):
@contextmanager
def session(self, *, client_id=None):
relay = RelayConnection(self.serial_number, self.timeout)
relay = RelayConnection(self.serial_number, self.timeout, self.account_owner)
try:
self._apply(relay.identity)
yield CloudMQTT(relay, self.report_topic, self.timeout)
@@ -230,7 +231,7 @@ def resolved_connection(connection):
"""A LAN-shaped copy of a cloud connection for camera code that dials the printer."""
if not is_cloud(connection):
return connection
relay = RelayConnection(connection.get('bambu_serial_number') or '', 20)
relay = RelayConnection(connection.get('bambu_serial_number') or '', 20, connection.get('_bambu_account_owner'))
relay.close()
identity = relay.identity
if not identity.get('ip') or not identity.get('access_code'):
@@ -267,7 +268,8 @@ async def relay_stream(connection):
raise ValueError('Invalid Bambu cloud relay line')
return value
await write({'token': token, 'dev_id': connection.get('bambu_serial_number') or ''})
await write({'token': token, 'dev_id': connection.get('bambu_serial_number') or '',
'owner': connection.get('_bambu_account_owner')})
async with asyncio.timeout(30):
hello = await read()
if not hello.get('ok'):
+180
View File
@@ -0,0 +1,180 @@
"""Account-scoped Bambu preset sync for shared library templates."""
import asyncio
from dataclasses import dataclass
from hashlib import sha256
import json
import logging
import time
from .orca_cloud_presets import CloudPresetCodec, SCOPES
from .orca_profile_chunks import MAX_PROFILES, RESULT_BYTES, encoded_size
from .profile_bundles import NAME
LOG = logging.getLogger(__name__)
INTERVAL = 120
METADATA = {'name', 'type', 'version', 'inherits', 'filament_id', 'base_id',
'user_id', 'setting_id', 'created_time', 'updated_time', 'update_time'}
@dataclass(frozen=True)
class RemotePreset:
id: str
name: str
content: dict
updated_time: int = 0
@property
def fingerprint(self):
content = {key: value for key, value in self.content.items()
if key not in {'updated_time', 'update_time', 'created_time'}}
return sha256(json.dumps(content, sort_keys=True).encode()).hexdigest()
class BambuPresetSync:
def __init__(self, store, worker, call):
self.store, self.worker, self.call = store, worker, call
self.codec = CloudPresetCodec(worker)
self.wake = asyncio.Event()
self.lock = asyncio.Lock()
self.status = {}
with store.connection() as db:
db.executescript('''
CREATE TABLE IF NOT EXISTS bambu_preset_preferences (
account TEXT PRIMARY KEY, enabled INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS bambu_preset_links (
account TEXT NOT NULL, remote_id TEXT NOT NULL,
local_id TEXT NOT NULL, revision INTEGER NOT NULL, fingerprint TEXT NOT NULL,
PRIMARY KEY(account, remote_id), UNIQUE(local_id)
);
''')
def enabled(self, account):
with self.store.connection() as db:
row = db.execute('SELECT enabled FROM bambu_preset_preferences WHERE account=?', (account,)).fetchone()
return row is None or bool(row['enabled'])
def state(self, account):
return {'enabled': self.enabled(account), **self.status.get(account, {})}
def configure(self, account, enabled):
with self.store.connection() as db:
db.execute('INSERT OR REPLACE INTO bambu_preset_preferences VALUES (?,?)', (account, enabled))
if enabled:
self.wake.set()
async def run(self):
while True:
self.wake.clear()
try:
state = await self.call('status')
account = state.get('user_id') if state.get('logged_in') else None
if account and self.enabled(account):
self.status[account] = {**self.status.get(account, {}), 'running': True}
try:
async with self.lock:
if self.enabled(account):
result = await self.sync(account)
previous = self.status[account].get('catalog_changed_at')
if result.pop('catalog_changed', False):
previous = time.time()
self.status[account] = {'last_sync': time.time(), 'catalog_changed_at': previous, **result}
except Exception:
LOG.warning('Bambu preset synchronization failed', exc_info=True)
self.status[account]['failed'] = True
finally:
self.status[account]['running'] = False
except Exception:
LOG.debug('Bambu preset synchronization is waiting for an account', exc_info=True)
try:
await asyncio.wait_for(self.wake.wait(), INTERVAL)
except TimeoutError:
pass
async def sync(self, account):
version = json.loads((self.worker.resources / 'profiles' / 'BBL.json').read_text(encoding='utf-8'))['version']
reply = await self.call('user_presets', bundle_version=version, include_identity=True)
if reply['account'] != account or not self.enabled(account):
return {}
values = reply['presets']
if len(values) > MAX_PROFILES or encoded_size(values) > RESULT_BYTES:
raise ValueError('Bambu preset collection exceeds the synchronization limit')
remote = []
for name, content in values.items():
if (NAME.fullmatch(name) and name == name.strip() and content.get('type') in SCOPES
and content.get('setting_id') and content.get('user_id', account) == account
and content.keys() - METADATA):
updated = content.get('updated_time', '')
remote.append(RemotePreset(content['setting_id'], name, {**content, 'name': name},
int(updated) if updated.isdecimal() else 0))
with self.store.connection() as db:
records = self.store.template_profiles(db=db)
links = {row['remote_id']: row for row in db.execute(
'SELECT * FROM bambu_preset_links WHERE account=?', (account,))}
names = {(row['scope'], row['name']) for row in db.execute('SELECT scope,name FROM user_profiles')}
by_id = {record['id']: record for record in records}
pull, push = [], []
conflicts = 0
catalog_changed = False
for preset in remote:
scope = SCOPES[preset.content['type']]
link = links.get(preset.id)
if link is None:
if (scope, preset.name) in names:
conflicts += 1
else:
pull.append((preset, None))
continue
local = by_id.get(link['local_id'])
if local is None or (local['scope'], local['name']) != (scope, preset.name):
conflicts += 1
continue
remote_changed = preset.fingerprint != link['fingerprint']
local_changed = local['revision'] != link['revision']
if local_changed and remote_changed:
conflicts += 1
elif remote_changed:
pull.append((preset, local))
elif local_changed:
push.append((preset, local))
if pull:
inspected = await self.codec.inspect([preset for preset, _ in pull], records, account)
if not self.enabled(account):
return {}
with self.store.connection() as db:
db.execute('BEGIN IMMEDIATE')
current = {record['id']: record for record in self.store.template_profiles(db=db)}
occupied = {(row['scope'], row['name']) for row in db.execute('SELECT scope,name FROM user_profiles')}
for (preset, local), value in zip(pull, inspected, strict=True):
payload = value['payload']
identity = payload['scope'], payload['name']
if local is None and identity in occupied or local is not None and (
local['id'] not in current or current[local['id']]['revision'] != local['revision']):
conflicts += 1
continue
saved = self.store.save_template_profile(*identity, payload, None, None, 0,
profile_id=local['id'] if local else None, expected=local['revision'] if local else None, db=db)
catalog_changed = True
db.execute('INSERT INTO bambu_preset_links VALUES (?,?,?,?,?) ON CONFLICT(account, remote_id) DO UPDATE SET revision=excluded.revision,fingerprint=excluded.fingerprint',
(account, preset.id, saved['id'], saved['revision'], preset.fingerprint))
if push:
exported = await self.codec.export([local for _, local in push])
for (preset, local), value in zip(push, exported, strict=True):
if not self.enabled(account):
break
try:
current = self.store.user_profile(local['id'])
except KeyError:
continue
if current['revision'] != local['revision']:
continue
options = {key: field for key, field in value['content'].items()
if key not in {'user_id', 'setting_id', 'created_time', 'updated_time', 'update_time'}}
content = {**preset.content, **options, 'name': preset.name}
fingerprint = RemotePreset(preset.id, preset.name, content).fingerprint
await self.call('update_user_preset', account=account, setting_id=preset.id, name=preset.name,
content=content)
with self.store.connection() as db:
db.execute('UPDATE bambu_preset_links SET revision=?,fingerprint=? WHERE account=? AND remote_id=?',
(local['revision'], fingerprint, account, preset.id))
return {'conflicts': conflicts, 'catalog_changed': catalog_changed}
@@ -183,6 +183,13 @@ def install_filament_product_api(app,store):
values=await app.state.template_catalog.choices(owned['template_name'])
return [item for item in values['filaments'] if item['compatible'] and item.get('filament_type')==product['material']]
@app.get('/api/v1/filament-product-template')
async def product_template(name: str = Query(min_length=1,max_length=512)):
snapshot = await app.state.template_catalog.snapshot('filament', name)
if snapshot is None:
raise HTTPException(404, 'The filament template is unavailable')
return service.legacy_metadata(snapshot.get('display_name') or name.split('/')[-1], snapshot)
@app.get('/api/v1/filament-products/{product_id}/profile-sources')
async def sources(product_id:uuid.UUID,machine_id:uuid.UUID,profile_id:str):
return await profile_sources(str(product_id),str(machine_id),profile_id)
+56 -4
View File
@@ -8,7 +8,7 @@ import uuid
import zipfile
from fastapi import File, HTTPException, UploadFile, Query
from fastapi.responses import FileResponse
from fastapi.responses import FileResponse, Response
from pydantic import BaseModel, ConfigDict, Field, StrictInt, ValidationError, model_validator
from typing import Literal
@@ -384,7 +384,11 @@ class ImportQueue:
for path, report in zip(payload['paths'], reports):
if Path(path).suffix.lower() in {'.3mf', '.amf', '.step', '.stp'}:report['suggested_units'] = 'none'
payload['reports'] = reports
if any(report.get('suggested_units') != 'none' or report.get('multipart') or report.get('step') or report.get('texture', {}).get('available') for report in reports):
if payload.get('automatic_open'):
payload['options'] = [ImportOptions(
texture=TextureImportOptions(mode='skip') if report.get('texture', {}).get('available') else None,
).model_dump(exclude_none=True) for report in reports]
elif any(report.get('suggested_units') != 'none' or report.get('multipart') or report.get('step') or report.get('texture', {}).get('available') for report in reports):
self.update(job_id, 'waiting_options', expected={'running'}, progress=35, payload=payload)
return
if not payload.get('staged'):
@@ -510,8 +514,11 @@ class ImportQueue:
state['imported_project'] = True
payload.update(staged=str(snapshot), state=state, scaling=state.get('import_scaling'))
if state.get('import_scaling', {}).get('pending'):
self.update(job_id, 'waiting_scale', expected={'running'}, progress=80, payload=payload)
return
if payload.get('automatic_open'):
state['import_scaling']['pending'] = []
else:
self.update(job_id, 'waiting_scale', expected={'running'}, progress=80, payload=payload)
return
state, snapshot = payload['state'], Path(payload['staged'])
if payload.get('accept_scale'):
scaled = directory / (uuid.uuid4().hex + '.3mf')
@@ -733,6 +740,51 @@ def install_import_api(app, queue, receive_upload, plate_type, filament_profiles
if not committed and attempt_root is not None:
await file_work(shutil.rmtree, attempt_root, ignore_errors=True)
@app.post('/api/v1/imports/open-model', status_code=201, response_model=ImportResponse)
async def open_model(file: UploadFile, response: Response, machine_id: uuid.UUID | None = None,
profile_id: str | None = Query(default=None, min_length=1, max_length=64)):
name = Path((file.filename or '').replace('\\', '/')).name
suffix = Path(name).suffix.lower()
if suffix not in {'.3mf', '.stl', '.step', '.stp'}:
raise HTTPException(422, 'Choose a 3MF, STL or STEP model')
if profile_id is not None and machine_id is None:
raise HTTPException(422, 'Select a printer for this profile')
machines = queue.machines.list()
if machine_id is not None:
selected = next((machine for machine in machines if machine['id'] == str(machine_id)), None)
if selected is None:
raise HTTPException(404, 'Printer not found')
preference = {}
else:
preference = queue.store.machine_preference() or {}
selected = next((machine for machine in machines if machine['id'] == preference.get('machine_id')), None)
if selected is None and len(machines) == 1:
selected, preference = machines[0], {}
if selected is None:
raise HTTPException(422, 'Choose a physical printer in Web Slicer before opening external models')
profiles = selected['profiles']
target_profile = profile_id or preference.get('profile_id')
owner = next((profile for profile in profiles if profile['id'] == target_profile), None)
if owner is None and profile_id is None:
preference = {}
owner = next((profile for profile in profiles if profile['id'] == selected['last_profile_id']), None)
if owner is None and len(profiles) == 1:
owner = profiles[0]
if owner is None:
raise HTTPException(422, 'Choose a printer profile before opening external models')
selection = MachineSelection(machine_id=selected['id'], profile_id=owner['id'],
process_id=preference.get('process_id'), filament_ids=preference.get('filament_ids'))
try:
payload = await import_payload(StartImport(names=[name], machine=selection,
three_mf_mode='geometry' if suffix == '.3mf' else None))
except KeyError as error:
raise HTTPException(422, 'The selected printer preset is unavailable') from error
payload['automatic_open'] = True
job = queue.create(payload)
accepted = await upload(job['id'], [file])
response.headers['Location'] = f"/?import-job={job['id']}"
return accepted
@app.post('/api/v1/import-archives', status_code=201, response_model=ImportArchive)
async def archive_upload(file: UploadFile, request_id: str | None = Query(default=None, pattern=r'^[0-9a-f]{32}$')):
async with archive_lock:
+1
View File
@@ -25,6 +25,7 @@ def connect_printer(connection, *, credential_database=None, **options):
if spec.id == 'bambu_lan' and connection.get('bambu_transport') == 'cloud':
from .bambu_cloud_link import BambuCloudLink
return BambuCloudLink(serial_number=connection.get('bambu_serial_number') or '',
account_owner=connection.get('_bambu_account_owner'),
printer_model=connection.get('printer_model', ''), **options)
if spec.id == 'bambu_lan':
from .bambu_lan import BambuLAN
+56 -7
View File
@@ -1,4 +1,5 @@
"""Native preset file conversion with reviewed, atomic shared-library imports."""
import asyncio
import hashlib
import json
from pathlib import Path, PurePosixPath
@@ -397,10 +398,51 @@ def install_profile_bundle_api(app, store, worker, native_user_profiles, receive
@app.post('/api/v1/user-profile-imports', response_model=ImportPlan, status_code=201)
async def stage(file: UploadFile, preserve_namespace: bool = Form(default=True),
replace_package: bool = Form(default=False)):
async def receive(directory):
return await receive_upload(file, directory, LIMIT)
return await stage_source(receive, preserve_namespace, replace_package)
@app.post('/api/v1/user-profile-imports/bambu-cloud', response_model=ImportPlan, status_code=201)
async def stage_bambu_cloud():
host = app.state.bambu_account_host()
if host is None or not host.cloud:
raise HTTPException(404, 'Bambu Lab cloud requires a cloud-enabled build')
async def receive(directory):
from .bambu_cloud import REPLY_TIMEOUT
try:
bundle = json.loads((worker.resources / 'profiles' / 'Custom.json').read_text(encoding='utf-8'))
reply = await asyncio.wait_for(asyncio.to_thread(host.call, 'user_presets',
bundle_version=bundle['version']), REPLY_TIMEOUT)
except TimeoutError as error:
raise HTTPException(504, 'Bambu did not answer in time') from error
except (RuntimeError, ValueError) as error:
raise HTTPException(503, str(error)) from error
source = directory / 'bambu-lab-presets.zip'
kinds = {'printer': 'machine', 'print': 'process', 'filament': 'filament'}
metadata = {'type', 'name', 'version', 'inherits', 'filament_id', 'created_time', 'updated_time', 'update_time', 'base_id'}
total = count = 0
with zipfile.ZipFile(source, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
for name, values in sorted(reply['presets'].items()):
kind = kinds.get(values.get('type'))
if kind is None or not values.keys() - metadata:
continue
data = json.dumps({**values, 'name': name, 'type': kind}, ensure_ascii=False).encode()
total += len(data)
count += 1
if len(data) > 2 * 1024 * 1024 or total > LIMIT or count > 256:
raise HTTPException(422, 'The Bambu Lab preset collection is too large to import')
archive.writestr(f'preset-{count}.json', data)
if not count:
raise HTTPException(422, 'There are no printer, process or filament presets on this Bambu Lab account')
return source
return await stage_source(receive, False, False, cloud=True)
async def stage_source(receive, preserve_namespace, replace_package, *, cloud=False):
await capable()
directory = Path(tempfile.mkdtemp(prefix='preset-import-', dir=store.root / 'work'))
try:
source = await receive_upload(file, directory, LIMIT)
source = await receive(directory)
if source.suffix.lower() not in {'.json', '.zip', '.orca_printer', '.orca_filament', '.orca_bundle'}:
raise HTTPException(422, 'Choose JSON, ZIP or an Orca preset bundle')
records = store.user_profiles()
@@ -414,12 +456,19 @@ def install_profile_bundle_api(app, store, worker, native_user_profiles, receive
preserve_namespace=preserve_namespace, bundle_metadata=metadata)
except (ValueError, zipfile.BadZipFile, NotImplementedError, RuntimeError) as error:
raise HTTPException(422, 'Invalid preset file: ' + str(error)) from error
files = []
for index, (_, scope, document) in enumerate(entries):
target = directory / f'profile-{index}.json'
target.write_text(json.dumps(document, ensure_ascii=False), encoding='utf-8')
files.append({'scope': scope, 'file': str(target)})
result = await worker.run('profile_files', action='inspect', files=files, user_profiles=native_user_profiles(templates))
users = native_user_profiles(templates)
if cloud:
kinds = {'printer': 'printer', 'process': 'print', 'filament': 'filament'}
profiles = [{'scope': scope, 'name': document['name'], 'content': {**document, 'type': kinds[scope]}}
for _, scope, document in entries]
result = await worker.run('profile_files', action='cloud_inspect', profiles=profiles, user_profiles=users)
else:
files = []
for index, (_, scope, document) in enumerate(entries):
target = directory / f'profile-{index}.json'
target.write_text(json.dumps(document, ensure_ascii=False), encoding='utf-8')
files.append({'scope': scope, 'file': str(target)})
result = await worker.run('profile_files', action='inspect', files=files, user_profiles=users)
existing = {(r['scope'], r['name']): {'id': r['id'], 'revision': r['revision']} for r in templates}
plan = {'id': uuid.uuid4().hex, 'filename': source.name, 'sha256': hashlib.sha256(source.read_bytes()).hexdigest(),
'library_token': store.library_token(records), 'preserve_namespace': preserve_namespace, 'items': []}
+12 -2
View File
@@ -699,8 +699,18 @@ class Store:
row = db.execute("SELECT revision, data FROM printer_settings WHERE id=1").fetchone()
else:
row = db.execute('SELECT revision, data FROM saved_printers WHERE id=? AND deleted=0', (printer_id,)).fetchone()
return {**json.loads(row['data']), 'revision': row['revision'],
**({'id': printer_id} if printer_id is not None else {})} if row else None
if not row:
return None
value = {**json.loads(row['data']), 'revision': row['revision']}
if printer_id is not None:
value['id'] = printer_id
access = getattr(self, 'access', None)
if access and access.auth.required and value.get('bambu_transport') == 'cloud':
owner = db.execute("SELECT user_id FROM resource_owners WHERE kind='machine' AND resource_id=?",
(printer_id,)).fetchone()
if owner:
value['_bambu_account_owner'] = owner['user_id']
return value
def printers(self):
with self.connection() as db:
@@ -40,6 +40,7 @@ def test_unavailable_without_the_cloud_build(unconfigured):
assert unconfigured.get('/api/v1/bambu-cloud').json() == {'available': False}
assert unconfigured.post('/api/v1/bambu-cloud/login', json={'ticket': 'ABCD1234'}).status_code == 404
assert unconfigured.post('/api/v1/bambu-cloud/logout').status_code == 404
assert unconfigured.post('/api/v1/user-profile-imports/bambu-cloud').status_code == 404
@pytest.mark.parametrize('body', [{}, {'ticket': 'ab', 'session': {'a': 1}}, {'ticket': 'a b!'},
@@ -0,0 +1,65 @@
from pathlib import Path
from types import SimpleNamespace
from fastapi.testclient import TestClient
from orca_web.app import create_app
from test_machine_library import variant
def test_desktop_pairing_is_per_user_and_cannot_be_replayed(tmp_path, monkeypatch):
monkeypatch.setenv('ORCA_AUTH_REQUIRED', 'true')
monkeypatch.setenv('ORCA_AUTH_SECURE_COOKIE', 'true')
monkeypatch.delenv('ORCA_BAMBU_CLOUD_HOST', raising=False)
monkeypatch.delenv('ORCA_BAMBU_CLOUD_PLUGIN', raising=False)
calls = []
active = set()
def configured(root):
def call(operation, **fields):
if operation == 'login_ticket':
calls.append((Path(root).name, fields))
active.add(root)
return {'logged_in': root in active, **({'user_id': 'bambu-user'} if root in active else {})}
return SimpleNamespace(cloud=True, plugin_version='02.09.01', call=call,
close=lambda: None, data_dir=Path(root) / 'bambu-cloud')
monkeypatch.setattr('orca_web.bambu_cloud.configured_host', configured)
app = create_app(data=tmp_path, executable=tmp_path / 'missing-worker')
password = 'desktop-pairing-test-password'
admin = app.state.auth.create_user('admin', password, admin=True)
app.state.auth.create_user('other', password)
printer = app.state.machines.create('Cloud printer', [variant()],
connection={'type': 'bambu_lan', 'bambu_transport': 'cloud',
'host': 'http://bambu-cloud.invalid/', 'bambu_serial_number': 'ABC12345'},
owner_id=admin['id'])
assert app.state.store.printer(printer['id'])['_bambu_account_owner'] == admin['id']
base = 'https://testserver'
route = '/api/v1/bambu-cloud/desktop-login'
with TestClient(app, base_url=base) as browser, TestClient(app, base_url=base) as helper:
assert helper.post(route).status_code == 401
login = browser.post('/api/v1/auth/login', json={'username': 'admin', 'password': password},
headers={'Origin': base, 'X-Orca-CSRF': 'login'})
assert login.status_code == 200, login.text
headers = {'Origin': base, 'X-Orca-CSRF': login.json()['csrf_token']}
issued = browser.post(route, headers=headers)
assert issued.status_code == 200, issued.text
credential = {'Authorization': 'Bearer ' + issued.json()['code']}
assert helper.post(route + '/redeem', json={'ticket': 'TEST'}, headers={**credential, 'Origin': base}).status_code == 403
assert helper.post(route + '/redeem', json={'ticket': 'TEST'}, headers=credential).status_code == 204
assert helper.post(route + '/redeem', json={'ticket': 'TEST'}, headers=credential).status_code == 403
assert calls == [(admin['id'], {'ticket': 'TEST'})]
assert browser.get('/api/v1/bambu-cloud').json()['logged_in'] is True
with TestClient(app, base_url=base) as other:
signed_in = other.post('/api/v1/auth/login', json={'username': 'other', 'password': password},
headers={'Origin': base, 'X-Orca-CSRF': 'login'})
assert signed_in.status_code == 200
assert other.get('/api/v1/bambu-cloud').json()['logged_in'] is False
code = other.post(route, headers={'Origin': base, 'X-Orca-CSRF': signed_in.json()['csrf_token']})
assert code.status_code == 200
assert code.json()['code'] != issued.json()['code']
credential = {'Authorization': 'Bearer ' + browser.post(route, headers=headers).json()['code']}
assert browser.post('/api/v1/auth/logout', headers=headers).status_code == 204
assert helper.post(route + '/redeem', json={'ticket': 'TEST'}, headers=credential).status_code == 403
assert len(calls) == 1
@@ -0,0 +1,69 @@
import asyncio
from types import SimpleNamespace
from orca_web.bambu_preset_sync import BambuPresetSync
from orca_web.store import Store
def test_bambu_sync_links_updates_and_quarantines_conflicts(tmp_path):
asyncio.run(check_bambu_sync(tmp_path))
async def check_bambu_sync(tmp_path):
resources = tmp_path / 'resources'
(resources / 'profiles').mkdir(parents=True)
(resources / 'profiles' / 'BBL.json').write_text('{"version":"02.04.00.00"}')
store = Store(tmp_path / 'data')
remote = {'name': 'Lab PLA', 'type': 'filament', 'version': '2.4.0',
'setting_id': 'remote-id', 'filament_type': 'PLA', 'filament_density': '1.24'}
writes = []
async def call(operation, **body):
if operation == 'user_presets':
return {'account': 'account', 'presets': {remote['name']: dict(remote)}}
assert operation == 'update_user_preset' and body['account'] == 'account'
assert body['setting_id'] == 'remote-id'
writes.append(body)
remote.update(body['content'])
class Codec:
async def inspect(self, presets, records, account):
return [{'payload': {'scope': 'filament', 'name': preset.name,
'config': {'filament_density': preset.content['filament_density']}}} for preset in presets]
async def export(self, records):
return [{'content': record['payload']['config']} for record in records]
sync = BambuPresetSync(store, SimpleNamespace(resources=resources), call)
sync.codec = Codec()
assert sync.enabled('account')
def change_local(density):
record, = store.template_profiles()
return store.save_template_profile('filament', record['name'],
{'scope': 'filament', 'name': record['name'], 'config': {'filament_density': density}},
None, None, 0, profile_id=record['id'], expected=record['revision'])
assert (await sync.sync('account'))['catalog_changed']
imported, = store.template_profiles()
assert not (await sync.sync('account'))['catalog_changed']
assert store.template_profiles()[0]['revision'] == imported['revision']
remote['filament_density'] = '1.25'
assert (await sync.sync('account'))['catalog_changed']
assert store.template_profiles()[0]['payload']['config']['filament_density'] == '1.25'
local = change_local('1.26')
assert (await sync.sync('account'))['conflicts'] == 0
assert remote['filament_density'] == '1.26'
assert not (await sync.sync('account'))['catalog_changed']
assert store.template_profiles()[0]['revision'] == local['revision']
change_local('1.27')
remote['filament_density'] = '1.28'
assert (await sync.sync('account'))['conflicts'] == 1
assert len(writes) == 1
assert store.template_profiles()[0]['payload']['config']['filament_density'] == '1.27'
sync.configure('account', False)
assert not sync.enabled('account')
assert sync.enabled('other-account')
@@ -0,0 +1,30 @@
"""External model uploads use the same durable queue with safe defaults."""
import pytest
from import_setup import import_machine, wait
from test_placement_api import ROOT, client, pytestmark
@pytest.mark.parametrize('fixture', [
'tests/data/test_stl/ASCII/20mmbox-LF.stl',
'tests/data/curved_compound.step',
'tests/data/test_3mf/prusa-geometry.3mf',
])
def test_open_model_creates_a_project_without_import_decisions(client, fixture):
machine = import_machine(client)
source = ROOT / fixture
response = client.post('/api/v1/imports/open-model', files={'file': (source.name, source.read_bytes())})
assert response.status_code == 201, response.text
task = response.json()
assert response.headers['Location'] == '/?import-job=' + task['id']
task = wait(client, task, {'completed', 'waiting_options', 'waiting_scale', 'waiting_texture'})
assert task['status'] == 'completed', task
project = client.get('/api/v1/projects/' + task['result']['project_id']).json()
assert project['state']['objects']
assert project['state']['machine_binding']['machine_id'] == machine['machine_id']
def test_open_model_requires_supported_file_and_printer(client):
assert client.post('/api/v1/imports/open-model', files={'file': ('note.txt', b'note')}).status_code == 422
assert client.post('/api/v1/imports/open-model', files={'file': ('cube.stl', b'cube')}).status_code == 422
assert client.get('/api/v1/imports').json() == []
@@ -154,3 +154,23 @@ def test_product_copy_rejects_calibration_for_another_known_material(setup_api):
assert app.state.store.user_profiles()==before
assert ca.get('/api/v1/filament-products/'+target['id']).json()['profiles']==[]
ca.close()
def test_filament_product_draft_from_preset_without_a_printer(setup_api, monkeypatch):
app, client, _, _, _, student, _, _ = setup_api
async def snapshot(scope, name):
assert (scope, name) == ('filament', 'Example PETG @ Example Printer')
return {'config': {'filament_vendor': 'Example', 'filament_type': 'PETG', 'filament_density': '1.27'}}
monkeypatch.setattr(app.state.template_catalog, 'snapshot', snapshot)
with client(student) as c:
response = c.get('/api/v1/filament-product-template', params={'name': 'Example PETG @ Example Printer'})
assert response.status_code == 200, response.text
draft = response.json()
assert (draft['name'], draft['vendor'], draft['material'], draft['density']) == ('Example PETG', 'Example', 'PETG', 1.27)
library = c.post('/api/v1/filament-libraries/default').json()
created = c.post('/api/v1/filament-products', json={**draft, 'library_id': library['id']})
assert created.status_code == 201, created.text
assert created.json()['printer_ids'] == []
assert created.json()['profiles'] == []
+17
View File
@@ -30,6 +30,22 @@ RUN node /scripts/build-setting-layout.mjs \
&& node node_modules/typescript/bin/tsc --noEmit \
&& node scripts/build-frontends.mjs
FROM node:22-bookworm-slim AS desktop-helper
ENV UV_THREADPOOL_SIZE=1 GOMAXPROCS=2 NODE_OPTIONS="--v8-pool-size=1"
WORKDIR /helper
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates zip \
&& rm -rf /var/lib/apt/lists/*
COPY desktop/bambu-login/package*.json ./
RUN npm ci --ignore-scripts
COPY desktop/bambu-login ./
RUN npm run package -- --platform=linux --arch=x64 \
&& npm run package -- --platform=win32 --arch=x64 \
&& mkdir /downloads \
&& cd dist \
&& for package in WebSlicerBambuLogin-linux-x64 WebSlicerBambuLogin-win32-x64; do \
zip -q -r "/downloads/${package}.zip" "${package}" || exit 1; \
done
FROM nginx:stable-alpine AS static-base
ARG SOURCE_URL
ARG SOURCE_REVISION
@@ -50,3 +66,4 @@ FROM static-base
LABEL org.opencontainers.image.title="Web Slicer client"
COPY web/deploy/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=frontend /frontend/dist /usr/share/nginx/html
COPY --from=desktop-helper /downloads /usr/share/nginx/html/bambu-login
@@ -27,6 +27,7 @@ test('product library shares identity and creates independent compatible slicing
await expect(profiles).toContainText('Fine PLA '+info.project.name);
// New products do not require physical-spool IDs or an inventory service.
await library.getByRole('button',{name:'Add filament',exact:true}).click();
await page.getByRole('dialog',{name:'Choose filament preset'}).getByRole('button',{name:'Enter details manually'}).click();
await details.getByLabel('Name',{exact:true}).fill('PETG '+info.project.name);
await details.getByLabel('Material',{exact:true}).fill('PETG');
await details.getByLabel('Manufacturer',{exact:true}).fill('My vendor');
@@ -0,0 +1 @@
*.zip
+101 -13
View File
@@ -1,13 +1,15 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {api,jsonRequest} from './api';
import {api,apiUrl,jsonRequest} from './api';
import {ErrorNotice} from './ErrorNotice';
import {FileInput} from './FileInput';
import {t,useLanguage} from './i18n';
import type {AccountPrinter} from './BambuCloudConnection';
import type {Job} from './types';
export interface BambuCloudState {available:boolean;plugin_version?:string;logged_in?:boolean;user_id?:string;user_name?:string;cloud_connected?:boolean;printing?:boolean}
export interface BambuPresetSyncState {enabled:boolean;running?:boolean;last_sync?:number;failed?:boolean;conflicts?:number;catalog_changed_at?:number|null}
export interface BambuCloudState {preset_sync?:BambuPresetSyncState;personal_account?:boolean;available:boolean;plugin_version?:string;logged_in?:boolean;user_id?:string;user_name?:string;cloud_connected?:boolean;printing?:boolean}
interface PrinterStatus {gcode_state?:string;mc_percent?:number;mc_remaining_time?:number;subtask_name?:string;nozzle_temper?:number;bed_temper?:number;print_error?:number;updated?:number;authorization_control?:boolean|null}
interface CloudPrinter {dev_id:string;name:string;model?:string|null;online:boolean;print_status?:string|null;status:PrinterStatus|null}
interface CloudPrinter extends AccountPrinter {print_status?:string|null;status:PrinterStatus|null}
interface CloudPrint {status:{status:number;stage:string;code:number;msg:string}[];done:{rc:number;cancelled:boolean}|null;reason:'authorization_control'|'task_rejected'|'error'|null}
// The Bambu sign-in page hands the session only to a native WebView bridge, so
@@ -80,10 +82,35 @@ function SlicerKeySection() {
</details>;
}
export function BambuCloudAccount({close,state,changed,job}:{close:()=>void;state:BambuCloudState;changed:(value:BambuCloudState)=>void;job:Job|null}) {
const desktopPackages=[
{label:'Linux x64',url:import.meta.env.BASE_URL+'bambu-login/WebSlicerBambuLogin-linux-x64.zip'},
{label:'Windows x64',url:import.meta.env.BASE_URL+'bambu-login/WebSlicerBambuLogin-win32-x64.zip'},
];
function DesktopHelperDownloads(){
const [available,setAvailable]=useState<typeof desktopPackages|null>(null);
useEffect(()=>{
const controller=new AbortController();
void Promise.all(desktopPackages.map(async item=>{
try{
const response=await fetch(item.url,{method:'HEAD',signal:controller.signal});
const type=response.headers.get('content-type')?.toLowerCase();
return response.ok&&(type?.includes('zip')||type?.includes('octet-stream'))?item:null;
}catch{return null;}
})).then(values=>{if(!controller.signal.aborted)setAvailable(values.filter(item=>item!==null));});
return()=>controller.abort();
},[]);
if(!available)return null;
return available.length?<div className="about-actions">
{available.map(item=><a className="button" download key={item.url} href={item.url}>{t('Download {platform}',{platform:item.label})}</a>)}
</div>:<p className="bambu-account-muted">{t('The desktop helper packages are unavailable on this server.')}</p>;
}
export function BambuCloudAccount({close,state,changed,job,addPrinter,openPresets}:{close:()=>void;state:BambuCloudState;changed:(value:BambuCloudState)=>void;job:Job|null;addPrinter?:(printer:AccountPrinter)=>void;openPresets?:()=>void}) {
useLanguage();
const dialog=useRef<HTMLDialogElement>(null);
const [busy,setBusy]=useState(false),[error,setError]=useState<unknown>(null);
const [pairing,setPairing]=useState(''),[copied,setCopied]=useState(false),[pairingExpires,setPairingExpires]=useState(0);
const [printers,setPrinters]=useState<CloudPrinter[]|null>(null),[selected,setSelected]=useState('');
const [bedLeveling,setBedLeveling]=useState(true),[flowCalibration,setFlowCalibration]=useState(false),[timelapse,setTimelapse]=useState(false);
const [cloudPrint,setCloudPrint]=useState<{job:number;state:CloudPrint|null}|null>(null);
@@ -103,6 +130,38 @@ export function BambuCloudAccount({close,state,changed,job}:{close:()=>void;stat
.then(value=>setCloudPrint(current=>current&&{...current,state:value})).catch(setError);},2000);
return()=>window.clearInterval(timer);
},[cloudPrint]);
useEffect(()=>{
if(!pairing)return;
const controller=new AbortController();
const timer=window.setInterval(()=>{
void api<BambuCloudState>('/bambu-cloud',{signal:controller.signal}).then(value=>{
if(value.logged_in&&!controller.signal.aborted){setPairing('');changed(value);}
}).catch(()=>{});
},2500);
const expiry=window.setTimeout(()=>setPairing(''),Math.max(0,pairingExpires-Date.now()));
return()=>{controller.abort();window.clearInterval(timer);window.clearTimeout(expiry);};
},[pairing,pairingExpires,changed]);
async function startDesktopSignIn(){
setBusy(true);setError(null);setCopied(false);
try{
const value=await api<{code:string;expires_in:number;plugin_version?:string}>('/bambu-cloud/desktop-login',jsonRequest('POST',{}));
const url=new URL(apiUrl('/bambu-cloud/desktop-login/redeem'),location.href);
url.hash=new URLSearchParams({bambu_pairing:value.code,version:value.plugin_version??''}).toString();
setPairingExpires(Date.now()+value.expires_in*1000);setPairing(url.href);
}catch(reason){setError(reason);}finally{setBusy(false);}
}
async function cancelDesktopSignIn(){
setBusy(true);setError(null);
try{await api('/bambu-cloud/desktop-login',{method:'DELETE'});setPairing('');}
catch(reason){setError(reason);}finally{setBusy(false);}
}
async function configureSync(enabled?:boolean){
setBusy(true);setError(null);
try{
const value=await api<BambuPresetSyncState>('/bambu-cloud/preset-sync',jsonRequest(enabled===undefined?'POST':'PUT',enabled===undefined?{}:{enabled}));
changed({...state,preset_sync:value});
}catch(reason){setError(reason);}finally{setBusy(false);}
}
async function signOut(){
setBusy(true);setError(null);
try{changed(await api<BambuCloudState>('/bambu-cloud/logout',jsonRequest('POST',{})));setPrinters(null);}catch(reason){setError(reason);}finally{setBusy(false);}
@@ -121,19 +180,46 @@ export function BambuCloudAccount({close,state,changed,job}:{close:()=>void;stat
const signIn=()=>{window.location.href='/native/bambu-cloud-login?plugin_version='+encodeURIComponent(state.plugin_version??'');};
const printable=job?.status==='completed'&&job.result?.upload_format==='gcode_3mf';
const last=cloudPrint?.state?.status.at(-1);
return <dialog ref={dialog} className="about-dialog" aria-label={t('Bambu Lab account')} onCancel={event=>{event.preventDefault();close();}}>
return <dialog ref={dialog} className="about-dialog bambu-account-dialog" aria-label={t('Bambu Lab account')} onCancel={event=>{event.preventDefault();close();}}>
<header><h2>{t('Bambu Lab account')}</h2><button onClick={close}>{t('Close')}</button></header>
{state.logged_in
?<p role="status">{t('Signed in as {name}',{name:state.user_name||state.user_id||''})}</p>
:<p role="status">{t('Not signed in')}</p>}
:<p role="status">{t(state.available?'Not signed in':'Bambu Lab cloud requires a cloud-enabled build.')}</p>}
{error!=null&&<ErrorNotice error={error} onDismiss={()=>setError(null)}/>}
<div className="about-actions">
{state.logged_in
?<button disabled={busy} onClick={()=>{void signOut();}}>{t('Sign out')}</button>
:inAndroidApp()
?<button disabled={busy} onClick={signIn}>{t('Sign in to Bambu Lab')}</button>
:<p>{t('Signing in to Bambu Lab is available in the Android app.')}</p>}
</div>
{state.logged_in?<div className="about-actions"><button disabled={busy} onClick={()=>void signOut()}>{t('Sign out')}</button></div>:
state.available&&(inAndroidApp()
?<div className="about-actions"><button disabled={busy} onClick={signIn}>{t('Sign in to Bambu Lab')}</button></div>
:<section className="bambu-desktop-sign-in">
<h3>{t('Desktop helper')}</h3>
<p className="bambu-account-muted">{t('Download the helper, then create a pairing link and paste it into the app.')}</p>
<DesktopHelperDownloads/>
{pairing?<div className="bambu-pairing-fields">
<label>{t('Desktop pairing link')}<input readOnly value={pairing} onFocus={event=>event.currentTarget.select()}/></label>
<p className="bambu-account-muted">{t('Paste this link into the Web Slicer desktop helper. It expires after 10 minutes.')}</p>
<div className="about-actions">
<button className="primary" disabled={busy} onClick={()=>{void navigator.clipboard.writeText(pairing).then(()=>setCopied(true)).catch(setError);}}>{t(copied?'Copied':'Copy link')}</button>
<button disabled={busy} onClick={()=>void cancelDesktopSignIn()}>{t('Cancel')}</button>
</div>
</div>:<div className="about-actions">
<button className="primary" disabled={busy} onClick={()=>void startDesktopSignIn()}>{t('Create pairing link')}</button>
</div>}
</section>)}
{state.logged_in&&state.available&&!inAndroidApp()&&<section className="bambu-desktop-sign-in">
<h3>{t('Desktop helper')}</h3>
<DesktopHelperDownloads/>
</section>}
{state.logged_in&&state.personal_account&&<p>{t('Your Bambu Lab connection is private to your Web Slicer account. Automatic sync to the shared preset library is disabled.')}</p>}
{state.logged_in&&state.preset_sync&&<section>
<h3>{t('Preset synchronization')}</h3>
<label><input type="checkbox" checked={state.preset_sync.enabled} disabled={busy}
onChange={event=>void configureSync(event.target.checked)}/> {t('Sync Bambu Lab presets automatically')}</label>
{state.preset_sync.enabled&&<p role="status">{state.preset_sync.running?t('Synchronizing presets…'):
state.preset_sync.failed?t('Preset sync failed. It will retry automatically.'):
state.preset_sync.last_sync?t('Last synchronized: {time}',{time:new Date(state.preset_sync.last_sync*1000).toLocaleString()}):
t('Waiting for the first synchronization.')}</p>}
{!!state.preset_sync.conflicts&&<p role="status">{t('Presets needing review: {count}',{count:state.preset_sync.conflicts})}</p>}
<button type="button" disabled={busy||!state.preset_sync.enabled||state.preset_sync.running} onClick={()=>void configureSync()}>{t('Sync now')}</button>
</section>}
{state.logged_in&&<section>
<h3>{t('Printers on this account')}</h3>
{printers===null?<p role="status">{t('Loading…')}</p>
@@ -141,6 +227,7 @@ export function BambuCloudAccount({close,state,changed,job}:{close:()=>void;stat
:<ul>{printers.map(printer=><li key={printer.dev_id}><label>
<input type="radio" name="bambu-cloud-printer" checked={selected===printer.dev_id} onChange={()=>setSelected(printer.dev_id)}/>
{' '}{printer.name}{printer.model?` (${printer.model})`:''}{' — '}{describe(printer)}</label>
{addPrinter&&<button disabled={busy} onClick={()=>addPrinter(printer)}>{t('Add to printers')}</button>}
{printer.status?.authorization_control&&<div><small>{t('Verifies commands (Authorization Control): status works, but cloud printing and control need a slicer key.')}</small></div>}</li>)}</ul>}
{selected&&<>
<h3>{t('Print through Bambu Lab cloud')}</h3>
@@ -156,6 +243,7 @@ export function BambuCloudAccount({close,state,changed,job}:{close:()=>void;stat
<p><small>{t('Prints from the external spool; AMS mapping is not supported yet. Printers that verify commands also need a slicer key (see below).')}</small></p>
</>}
</section>}
{state.logged_in&&openPresets&&<button disabled={busy} onClick={openPresets}>{t('Import Bambu Lab presets')}</button>}
{state.logged_in&&<SlicerKeySection/>}
<p><small>{t('The sign-in page is Bambu Lab’s own; your password is entered there and is never seen by Web Slicer. Plugin {version}.',{version:state.plugin_version??''})}</small></p>
</dialog>;
+18 -26
View File
@@ -7,48 +7,40 @@ import {t} from './i18n';
// the account the backend looks up the printer's address and access code, so
// only the serial number is saved.
export const CLOUD_HOST='http://bambu-cloud.invalid/';
interface AccountPrinter {dev_id:string;name:string;model?:string|null;model_code?:string|null;online:boolean}
export interface AccountPrinter {dev_id:string;name:string;model?:string|null;model_code?:string|null;online:boolean}
export const CLOUD_TYPE='bambu_cloud';
export function cloudConnection(printer:AccountPrinter){
return {revision:0,type:'bambu_lan',bambu_transport:'cloud',host:CLOUD_HOST,auth_type:'api_key',
bambu_serial_number:printer.dev_id,printer_model:printer.model_code??''};
}
export const isCloudDraft=(draft:Record<string,unknown>)=>draft.type==='bambu_lan'&&draft.bambu_transport==='cloud';
export function BambuCloudConnection({draft,field}:{draft:Record<string,unknown>;field:(key:string,value:unknown)=>void}) {
const [available,setAvailable]=useState<boolean|null>(null);
export function BambuCloudConnection({draft,field,signedIn}:{draft:Record<string,unknown>;field:(key:string,value:unknown)=>void;signedIn:boolean}) {
const [printers,setPrinters]=useState<AccountPrinter[]|null>(null);
const [error,setError]=useState('');
const cloud=isCloudDraft(draft);
useEffect(()=>{api<{available:boolean;logged_in?:boolean}>('/bambu-cloud')
.then(value=>setAvailable(value.available&&!!value.logged_in)).catch(()=>setAvailable(false));},[]);
useEffect(()=>{
if(!cloud||!available)return;
setError('');
api<{printers:AccountPrinter[]}>('/bambu-cloud/printers').then(value=>setPrinters(value.printers))
.catch(reason=>setError(reason instanceof Error?reason.message:String(reason)));
},[cloud,available]);
if(!available&&!cloud)return null;
function transport(value:string){
field('bambu_transport',value);
field('host',value==='cloud'?CLOUD_HOST:'');
field('bambu_serial_number','');field('printer_model','');
}
if(!signedIn)return;
const controller=new AbortController();
api<{printers:AccountPrinter[]}>('/bambu-cloud/printers',{signal:controller.signal})
.then(value=>setPrinters(value.printers))
.catch(reason=>{if(!controller.signal.aborted)setError(reason instanceof Error?reason.message:String(reason));});
return()=>controller.abort();
},[signedIn]);
function choose(dev:string){
const printer=printers?.find(item=>item.dev_id===dev);
field('bambu_serial_number',dev);
if(printer?.model_code)field('printer_model',printer.model_code);
field('printer_model',printer?.model_code??'');
}
return <>
<label>{t('Connection')}<select value={cloud?'cloud':'lan'} onChange={event=>transport(event.target.value)}>
<option value="lan">{t('LAN (Developer Mode)')}</option>
<option value="cloud" disabled={!available}>{t('Bambu Lab account')}</option>
</select></label>
{cloud&&<>
{available===false&&<p>{t('Sign in to your Bambu Lab account in this app to use this connection.')}</p>}
{!signedIn&&<p>{t('Sign in to your Bambu Lab account in this app to use this connection.')}</p>}
{error&&<p role="alert">{error}</p>}
{printers&&<label>{t('Printer on the account')}<select required value={String(draft.bambu_serial_number??'')} onChange={event=>choose(event.target.value)}>
{signedIn&&printers&&<label>{t('Printer on the account')}<select required value={String(draft.bambu_serial_number??'')} onChange={event=>choose(event.target.value)}>
<option value="" disabled>{t('Select')}</option>
{printers.map(printer=><option key={printer.dev_id} value={printer.dev_id}>
{printer.name}{printer.model?` (${printer.model})`:''}{printer.online?'':` · ${t('Offline')}`}</option>)}
</select></label>}
<p className="connection-description">{t('Status and controls go through the Bambu Lab cloud. The camera and printer files are reached on the local network, so they work only when this device is on the printer’s network. Printers that verify commands (Authorization Control) need a slicer key for controls. Printing uses Bambu Lab account → Print through Bambu Lab cloud.')}</p>
</>}
</>;
}
+102
View File
@@ -0,0 +1,102 @@
import {useEffect,useRef,useState} from 'react';
import {api} from './api';
import {ErrorNotice} from './ErrorNotice';
import {t} from './i18n';
import type {MaterialTemplate} from './TemplateMaterialPicker';
interface Preset extends MaterialTemplate {source?:string}
const commonMaterials=['PLA','PETG','ABS','ASA','TPU'];
const pageSize=12;
const presetName=(preset:Preset)=>preset.display_name??preset.name;
export function FilamentPresetBrowser({busy,applyError,close,manual,apply}:{busy:boolean;applyError:string;close:()=>void;manual?:()=>void;apply:(name:string)=>void}){
const dialog=useRef<HTMLDialogElement>(null);
const [presets,setPresets]=useState<Preset[]|null>(null),[error,setError]=useState<unknown>(null),[attempt,setAttempt]=useState(0);
const [query,setQuery]=useState(''),[material,setMaterial]=useState(''),[vendor,setVendor]=useState(''),[limit,setLimit]=useState(pageSize);
const [selection,setSelection]=useState<string|null>(null),[variant,setVariant]=useState('');
useEffect(()=>{dialog.current?.showModal();},[]);
useEffect(()=>{
const abort=new AbortController();
void api<{filaments:Preset[]}>('/profiles',{signal:abort.signal}).then(result=>{
if(!abort.signal.aborted)setPresets(result.filaments.filter(item=>item.source!=='project'));
}).catch(reason=>{if(!abort.signal.aborted)setError(reason);});
return()=>abort.abort();
},[attempt]);
const materials=[...new Set(presets?.flatMap(preset=>preset.filament_type?[preset.filament_type]:[]))].sort();
const byMaterial=presets?.filter(preset=>!material||preset.filament_type===material)??[];
const vendors=[...new Set(byMaterial.flatMap(preset=>preset.filament_vendor?[preset.filament_vendor]:[]))].sort();
const words=query.trim().toLocaleLowerCase().split(/\s+/);
const groups=new Map<string,{name:string;material:string;vendor:string;presets:Preset[]}>();
if(material||vendor||query.trim()){
for(const preset of byMaterial){
const brand=preset.filament_vendor??'',type=preset.filament_type??'';
const searchable=[presetName(preset),brand,type].join(' ').toLocaleLowerCase();
if((vendor&&brand!==vendor)||!words.every(word=>searchable.includes(word)))continue;
const name=presetName(preset).split(' @',1)[0];
const key=JSON.stringify([type,brand,name]);
const group=groups.get(key)??{name,material:type,vendor:brand,presets:[]};
group.presets.push(preset);groups.set(key,group);
}
}
const results=[...groups].sort(([,a],[,b])=>a.name.localeCompare(b.name));
const selected=selection===null?undefined:groups.get(selection);
const chosen=selected?.presets.find(preset=>preset.name===variant);
const filtering=Boolean(material||vendor||query.trim());
const resetResults=()=>{setSelection(null);setVariant('');setLimit(pageSize);};
function changeMaterial(value:string){setMaterial(value);setVendor('');resetResults();}
function select(key:string,options:Preset[]){
setSelection(key);setVariant(options.length===1?options[0].name:'');
}
return <dialog ref={dialog} className="filament-preset-browser" aria-labelledby="filament-preset-title"
onCancel={event=>{event.preventDefault();if(!busy)close();}}>
<header className="filament-browser-header">
<div><h2 id="filament-preset-title">{t('Choose filament preset')}</h2>
<p>{t('Find a filament to fill in its library details.')}</p></div>
<button type="button" disabled={busy} onClick={close}>{t('Close')}</button>
</header>
<div className="filament-browser-body" aria-busy={busy||!presets&&!error}>
{applyError&&<p className="error" role="alert">{applyError}</p>}
{error!=null&&<><ErrorNotice error={error}/><button type="button" onClick={()=>{setError(null);setAttempt(value=>value+1);}}>{t('Retry')}</button></>}
{!presets&&!error&&<p role="status">{t('Loading filament presets…')}</p>}
{presets&&<fieldset className="filament-browser-controls" disabled={busy}>
<label>{t('Search presets')}<input autoFocus type="search" value={query} placeholder={t('e.g. Bambu PLA or PETG HF')}
onChange={event=>{setQuery(event.target.value);resetResults();}}/></label>
<div className="filament-browser-chips" aria-label={t('Popular materials')}>
{commonMaterials.filter(value=>materials.includes(value)).map(value=><button type="button" key={value}
aria-pressed={material===value} onClick={()=>changeMaterial(material===value?'':value)}>{value}</button>)}
</div>
<div className="filament-browser-filters">
<label>{t('Material')}<select value={material} onChange={event=>changeMaterial(event.target.value)}>
<option value="">{t('All materials')}</option>{materials.map(value=><option key={value}>{value}</option>)}
</select></label>
<label>{t('Manufacturer')}<select value={vendor} onChange={event=>{setVendor(event.target.value);resetResults();}}>
<option value="">{t('All manufacturers')}</option>{vendors.map(value=><option key={value}>{value}</option>)}
</select></label>
</div>
{!filtering&&<p className="filament-browser-empty">{t('Search by name or choose a material to browse presets.')}</p>}
{filtering&&<section aria-label={t('Matching items')}>
{results.length===0?<p className="filament-browser-empty">{t('No matching items...')}</p>:
<div className="filament-browser-results">{results.slice(0,limit).map(([key,group])=>
<button type="button" key={key} aria-pressed={selection===key} onClick={()=>select(key,group.presets)}>
<strong>{group.name}</strong>
<span>{[group.vendor,group.material].filter(Boolean).join(' · ')}</span>
</button>)}</div>}
{results.length>limit&&<button type="button" className="filament-browser-more" onClick={()=>setLimit(value=>value+pageSize)}>{t('Show more')}</button>}
</section>}
</fieldset>}
</div>
<footer className="filament-browser-footer">
{selected&&<div className="filament-browser-selection">
<strong>{selected.name}</strong>
{selected.presets.length>1&&<label>{t('Preset variant')}<select value={variant} disabled={busy} onChange={event=>setVariant(event.target.value)}>
<option value="" disabled>{t('Choose a variant')}</option>
{selected.presets.map(preset=><option value={preset.name} key={preset.name}>{presetName(preset)}</option>)}
</select></label>}
</div>}
<div className="printer-actions">
{manual&&<button type="button" disabled={busy} onClick={manual}>{t('Enter details manually')}</button>}
<button type="button" className="primary" disabled={busy||!chosen} onClick={()=>{if(chosen)apply(chosen.name);}}>{t('Use preset')}</button>
</div>
</footer>
</dialog>;
}
+22 -5
View File
@@ -1,15 +1,20 @@
import {useEffect,useState} from 'react';
import {useEffect,useRef,useState} from 'react';
import {api,jsonRequest,requestId} from './api';
import {t} from './i18n';
import {useError} from './uiErrors';
import {saveLibraryCopy,type LibrarySaveIntent,type Machine,type MachineProfile,type MachinePreset} from './machines';
import {emptyProduct,productData,productLabel,type FilamentLibrary,type FilamentProduct,type FilamentProductData} from './filamentProducts';
import type {MaterialTemplate} from './TemplateMaterialPicker';
import {FilamentPresetBrowser} from './FilamentPresetBrowser';
import './filamentProducts.css';
type Person={id:string;username:string};
type Template={name:string;display_name?:string;filament_vendor:string;filament_type:string};
type Template=MaterialTemplate;
export function FilamentProductLibrary({active,token,changed,editPreset,onDirty}:{active:boolean;token:number;changed:()=>void;
editPreset:(machine:Machine,profile:MachineProfile,preset:MachinePreset)=>void;onDirty:(dirty:boolean)=>void}){
const [browsing,setBrowsing]=useState<'new'|'replace'|null>(null);
const detailsName=useRef<HTMLInputElement>(null);
const focusDetails=useRef(false);
const [libraries,setLibraries]=useState<FilamentLibrary[]>([]),[products,setProducts]=useState<FilamentProduct[]>([]),[machines,setMachines]=useState<Machine[]>([]);
const [libraryId,setLibraryId]=useState(''),[selectedId,setSelectedId]=useState(''),[creating,setCreating]=useState(false);
const [draft,setDraft]=useState<FilamentProductData>(emptyProduct),[query,setQuery]=useState(''),[limit,setLimit]=useState(60);
@@ -28,6 +33,9 @@ export function FilamentProductLibrary({active,token,changed,editPreset,onDirty}
}
async function action(work:()=>Promise<void>){if(busy)return;setBusy(true);setError('');setNotice('');try{await work();}catch(reason){setError(reason);}finally{setBusy(false);}}
useEffect(()=>{if(active)void action(async()=>{await load();});},[active,token]);
useEffect(()=>{
if(creating&&!browsing&&!busy&&focusDetails.current){focusDetails.current=false;detailsName.current?.focus();}
},[creating,browsing,busy]);
useEffect(()=>{if(selected){setDraft(productData(selected));setCreating(false);}},[selected?.id,selected?.revision]);
useEffect(()=>{setOwner(library?.owner_id??'');setManagers(library?.managers??[]);setLibraryName(library?.name??'');},[library?.id,library?.revision]);
useEffect(()=>{
@@ -58,9 +66,12 @@ export function FilamentProductLibrary({active,token,changed,editPreset,onDirty}
if(!libraries.some(l=>l.id===libraryId&&l.can_manage)){
const value=await api<FilamentLibrary>('/filament-libraries/default',jsonRequest('POST',{}));setLibraryId(value.id);await load();
}
setSelectedId('');setCreating(true);setDraft({...emptyProduct});
setBrowsing('new');
});
}
function openDraft(value:FilamentProductData){
focusDetails.current=true;setSelectedId('');setDraft(value);setCreating(true);setBrowsing(null);
}
const visible=products.filter(p=>(!libraryId||p.library_id===libraryId)&&`${p.vendor} ${p.name} ${p.material}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()));
async function finishSave(intent:LibrarySaveIntent,recover:boolean){
await saveLibraryCopy(intent,recover,()=>{localStorage.removeItem(`orca-product-profile-save:${selectedId}`);setPending(null);});
@@ -68,7 +79,12 @@ export function FilamentProductLibrary({active,token,changed,editPreset,onDirty}
}
return <section className="filament-product-library" aria-label={t('Filament library')}>
<header className="product-library-heading"><div><h1>{t('Filament library')}</h1><p>{t('Filaments and their settings for your printers.')}</p></div><div className="printer-actions"><button disabled={busy} onClick={()=>void action(async()=>{if(!dirty||window.confirm(t('Discard unsaved changes?')))await load();})}>{t('Reload')}</button><button className="primary" disabled={busy} onClick={()=>void add()}>{t('Add filament')}</button></div></header>
{error&&<p className="error" role="alert">{error}</p>}{notice&&<p role="status">{t(notice)}</p>}{busy&&<p role="status">{t('Loading…')}</p>}
{browsing&&<FilamentPresetBrowser busy={busy} applyError={error} close={()=>{setBrowsing(null);setError('');}} manual={browsing==='new'?()=>openDraft({...emptyProduct}):undefined}
apply={name=>void action(async()=>{
if(browsing==='replace'&&dirty&&!window.confirm(t('Replace the filament draft with this preset?')))return;
openDraft(await api<FilamentProductData>('/filament-product-template?'+new URLSearchParams({name})));
})}/>}
{error&&!browsing&&<p className="error" role="alert">{error}</p>}{notice&&<p role="status">{t(notice)}</p>}{busy&&<p role="status">{t('Loading…')}</p>}
<div className="product-library-filters">
{libraries.length>1&&<label>{t('Library')}<select value={libraryId} disabled={busy} onChange={e=>{if(!dirty||window.confirm(t('Discard unsaved changes?'))){setLibraryId(e.target.value);setSelectedId('');setCreating(false);}}}>{libraries.map(l=><option key={l.id} value={l.id}>{l.name}</option>)}</select></label>}
<label>{t('Search')}<input type="search" value={query} onChange={e=>{setQuery(e.target.value);setLimit(60);}}/></label>
@@ -87,7 +103,8 @@ export function FilamentProductLibrary({active,token,changed,editPreset,onDirty}
});}}>
<h2>{t(creating?'Add filament':'Filament')}</h2>
<fieldset disabled={busy||!!selected&&!selected.can_manage}>
<label>{t('Name')}<input required maxLength={128} value={draft.name} onChange={e=>setDraft(v=>({...v,name:e.target.value}))}/></label>
{creating&&<div className="product-template-wizard"><button type="button" onClick={()=>{setError('');setBrowsing('replace');}}>{t('Start from a filament preset')}</button></div>}
<label>{t('Name')}<input ref={detailsName} required maxLength={128} value={draft.name} onChange={e=>setDraft(v=>({...v,name:e.target.value}))}/></label>
<label>{t('Manufacturer')}<input maxLength={128} value={draft.vendor} onChange={e=>setDraft(v=>({...v,vendor:e.target.value}))}/></label>
<label>{t('Material')}<input required maxLength={64} value={draft.material} onChange={e=>setDraft(v=>({...v,material:e.target.value}))}/></label>
<label>{t('Color')}<input type="color" value={draft.color} onChange={e=>setDraft(v=>({...v,color:e.target.value.toUpperCase()}))}/></label>
+16 -2
View File
@@ -45,8 +45,8 @@ function bundleManifest(files:File[]) {
}
const unfinished=new Set(['uploading','queued','running','waiting_options','waiting_texture','waiting_scale','interrupted','conflict','failed']);
export function Imports({request,consume,completed,historyContainer,project,schema,manage,libraryChanged}:{historyContainer?:HTMLElement|null;request:ImportRequest|null;consume:()=>void;completed:(task:ImportTask,explicit:boolean)=>Promise<void>;
project:Project|null;schema:Record<string,Option>;manage:()=>void;libraryChanged:()=>void}) {
export function Imports({request,consume,completed,historyContainer,project,schema,manage,libraryChanged,externalJob}:{historyContainer?:HTMLElement|null;request:ImportRequest|null;consume:()=>void;completed:(task:ImportTask,explicit:boolean)=>Promise<void>;
project:Project|null;schema:Record<string,Option>;manage:()=>void;libraryChanged:()=>void;externalJob?:string|null}) {
const [tasks,setTasks]=useState<ImportTask[]>([]),[error,setError,errorDetail]=useError();
const [pollError,setPollError,pollErrorDetail]=useError();
const [upload,setUpload]=useState<{id:string;percent:number}|null>(null);
@@ -63,6 +63,14 @@ export function Imports({request,consume,completed,historyContainer,project,sche
function adopt(task:ImportTask){
owned.current.add(task.id);setTasks(values=>[task,...values.filter(value=>value.id!==task.id)]);
}
useEffect(()=>{
if(!externalJob)return;
const controller=new AbortController();
void api<ImportTask>('/imports/'+encodeURIComponent(externalJob),{signal:controller.signal}).then(task=>{
if(!controller.signal.aborted){adopt(task);return refreshRef.current();}
}).catch(reason=>{if(!controller.signal.aborted)setError(reason);});
return()=>controller.abort();
},[externalJob]);
async function refresh(){
const values=await api<ImportTask[]>('/imports');setTasks(values);
const prompt=values.find(task=>owned.current.has(task.id)&&(task.status==='waiting_options'||task.status==='waiting_scale'||task.status==='waiting_texture')&&!prompted.current.has(`${task.id}:${task.status}:${task.updated}`));
@@ -138,6 +146,7 @@ export function Imports({request,consume,completed,historyContainer,project,sche
setDecision(null);await refresh();
}catch(reason){setError(reason);}finally{setBusy(false);}
}
const externalTask=externalJob&&tasks.find(task=>task.id===externalJob);
const currentDecision=decision&&tasks.find(task=>task.id===decision.id);
const pending=currentDecision&&decision?.status==='waiting_options'&&currentDecision.status==='waiting_texture'?{...currentDecision,status:'waiting_options'}:currentDecision;
const history=<div className="import-history">{tasks.filter((task,index)=>!dismissed.current.has(task.id)&&(unfinished.has(task.status)||index<5)).map(task=><div key={task.id}>
@@ -157,6 +166,11 @@ export function Imports({request,consume,completed,historyContainer,project,sche
{!unfinished.has(task.status)&&<button onClick={()=>{dismissed.current.add(task.id);setTasks([...tasks]);}}>{t("Ukryj import")}</button>}
</div>)}</div>;
return <section aria-label={t("Import modeli")}>
{externalTask&&externalTask.status!=='completed'&&<div className="archive-import-notice" role={externalTask.status==='failed'?'alert':'status'}>
<p>{externalTask.names.join(', ')} · {localize(externalTask.message||externalTask.status)}</p>
{['queued','running'].includes(externalTask.status)&&<progress max={100} value={externalTask.progress}/>}
{['failed','interrupted'].includes(externalTask.status)&&<button disabled={busy} onClick={()=>void act(externalTask,'retry')}>{t('Ponów import')}</button>}
</div>}
<ArchiveImport request={archiveRequest} consume={consume} accepted={adopt} project={project} schema={schema} manage={manage} libraryChanged={libraryChanged}/>
{machineImport&&!machineOpen&&<div className="archive-import-notice" role="status"><p>{t('An import is waiting for a physical printer.')}</p><button onClick={()=>setMachineOpen(true)}>{t('Resume import')}</button><button onClick={()=>setMachineImport(null)}>{t('Cancel')}</button></div>}
{machineImport&&<ImportMachineChoice names={machineImport.files.map(file=>file.name)} project={project} open={machineOpen} busy={busy}
+53 -8
View File
@@ -9,15 +9,23 @@ import {PrinterImage,TemplatePicker} from './PrinterTemplatePicker';
import {OwnedPrinterWizard} from './OwnedPrinterWizard';
import {machinePath,type Machine,type MachineProfile,type MachinePreset,type PresetScope,type PrinterTemplate} from './machines';
import './machineLibrary.css';
import {cloudConnection,type AccountPrinter} from './BambuCloudConnection';
import type {BambuCloudState} from './BambuCloudAccount';
import {readPrinterState} from './readPrinterState';
import {printerStateLabel,type PrinterStatusData} from './printerStatusTypes';
import {ResourceAccess} from './ResourceAccess';
import {useAuth} from './LocalAccount';
function AddMachine({templates,machine,done,cancel,onDirty}:{templates:PrinterTemplate[];machine?:Machine;
function AddMachine({templates,machine,cloud,initialPrinter,done,cancel,onDirty}:{templates:PrinterTemplate[];machine?:Machine;
cloud?:boolean;initialPrinter?:AccountPrinter;
done:(value:Machine)=>void;cancel:()=>void;onDirty:(value:boolean)=>void}) {
const identity=useRef(requestId());
const [template,setTemplate]=useState<PrinterTemplate|null>(null),[name,setName]=useState('');
const [accountPrinters,setAccountPrinters]=useState<AccountPrinter[]|null>(null);
const [accountPrinter,setAccountPrinter]=useState<AccountPrinter|undefined>(initialPrinter);
const bambuTemplates=templates.filter(value=>value.vendor==='BBL'||value.connection_hint==='bambu_lan');
const matchedModel=bambuTemplates.filter(value=>value.model==='Bambu Lab '+accountPrinter?.model);
const visibleTemplates=cloud?(matchedModel.length?matchedModel:bambuTemplates):templates;
const [template,setTemplate]=useState<PrinterTemplate|null>(null),[name,setName]=useState(initialPrinter?.name.slice(0,128)??'');
const [selectedTemplates,setSelectedTemplates]=useState<PrinterTemplate[]>([]),[variants,setVariants]=useState<Record<string,VariantDraft>>({});
const [connect,setConnect]=useState(false),[connectionDirty,setConnectionDirty]=useState(false),[pending,setPending]=useState(false),[error,setError]=useError();
const nameInput=useRef<HTMLInputElement>(null);
@@ -26,6 +34,16 @@ function AddMachine({templates,machine,done,cancel,onDirty}:{templates:PrinterTe
const valid=profiles.length>0&&!duplicateNames&&profiles.every(value=>value.name&&value.filament_templates.length&&variants[value.printer]?.ready);
useEffect(()=>{onDirty(Boolean(template||name||connectionDirty));},[template,name,connectionDirty]);
useEffect(()=>()=>onDirty(false),[]);
useEffect(()=>{
if(!cloud||initialPrinter)return;
const controller=new AbortController();
void api<{printers:AccountPrinter[]}>('/bambu-cloud/printers',{signal:controller.signal})
.then(value=>setAccountPrinters(value.printers)).catch(reason=>{if(!controller.signal.aborted)setError(reason);});
return()=>controller.abort();
},[cloud,initialPrinter]);
function selectAccountPrinter(printer:AccountPrinter){
setAccountPrinter(printer);setName(printer.name.slice(0,128));setTemplate(null);setSelectedTemplates([]);
}
function choose(value:PrinterTemplate){
const sameModel=template?.vendor===value.vendor&&template.model===value.model;
if(!sameModel&&connectionDirty&&!window.confirm(t('Discard unsaved changes?')))return;
@@ -38,6 +56,11 @@ function AddMachine({templates,machine,done,cancel,onDirty}:{templates:PrinterTe
setTemplate(value);setSelectedTemplates([value]);setVariants({[value.name]:{name:label,filament_templates:[],ready:false}});
setName(previous=>previous||value.model);setConnect(Boolean(value.connection_hint));setConnectionDirty(false);setError('');
}
useEffect(()=>{
if(!accountPrinter||template||!matchedModel.length)return;
const standard=matchedModel.find(value=>value.nozzles.length===1&&Number(value.nozzles[0])===0.4);
if(standard)choose(standard);
},[accountPrinter,template,templates]);
async function save(connection:Record<string,unknown>|null){
if(!template||pending)return;
if(!valid){setError('Select printer presets with unique names and at least one filament each.');return;}
@@ -63,18 +86,29 @@ function AddMachine({templates,machine,done,cancel,onDirty}:{templates:PrinterTe
return <section className="machine-wizard">
<header className="machine-heading"><h2>{t(machine?'Add profile':'Add printer')}</h2><button disabled={pending} onClick={cancel}>{t('Cancel')}</button></header>
{error&&<p role="alert">{localize(error)}</p>}
<TemplatePicker templates={templates} value={template} choose={choose} disabled={pending} multiple={!machine} selected={selectedTemplates}/>
{cloud&&<div>
{initialPrinter?<p>{initialPrinter.name}{initialPrinter.model&&' · '+initialPrinter.model}</p>:
accountPrinters?<label>{t('Printer on the account')}<select value={accountPrinter?.dev_id??''} disabled={pending}
onChange={event=>{const value=accountPrinters.find(printer=>printer.dev_id===event.target.value);if(value)selectAccountPrinter(value);}}>
<option value="" disabled>{t('Select')}</option>{accountPrinters.map(printer=><option key={printer.dev_id} value={printer.dev_id}>
{printer.name}{printer.model&&' · '+printer.model}</option>)}
</select></label>:!error&&<p role="status">{t('Loading…')}</p>}
{accountPrinters?.length===0&&<p>{t('No printers are bound to this Bambu Lab account.')}</p>}
{accountPrinter&&<p>{t('Choose the model and nozzle preset for this cloud printer.')}</p>}
</div>}
{(!cloud||accountPrinter)&&<TemplatePicker templates={visibleTemplates} value={template} choose={choose} disabled={pending} multiple={!machine} selected={selectedTemplates}/>}
{template&&<section className="machine-setup">
{!machine&&<label>{t('Nazwa drukarki')}<input ref={nameInput} required maxLength={128} value={name} disabled={pending} onChange={event=>setName(event.target.value)}/></label>}
{!machine&&<p>{t('Select the nozzle variants to create. Each has its own editable process and filament presets.')}</p>}
{selectedTemplates.map(value=><PrinterVariantSetup key={value.name} template={value} value={variants[value.name]} disabled={pending}
changed={draft=>setVariants(previous=>({...previous,[value.name]:draft}))}/>)}
{duplicateNames&&<p role="alert">{t('Preset names must be unique.')}</p>}
{!machine&&<label className="printer-checkbox"><input type="checkbox" disabled={pending} checked={connect} onChange={event=>{
{!machine&&!cloud&&<label className="printer-checkbox"><input type="checkbox" disabled={pending} checked={connect} onChange={event=>{
if(connectionDirty&&!window.confirm(t('Discard unsaved changes?')))return;
setConnect(event.target.checked);setConnectionDirty(false);
}}/>{t('Connection')}</label>}
{!machine&&connect?<PrinterPanel key={template.name} inline creation={{name,type:template.connection_hint,save:async value=>save(value)}} onDirty={setConnectionDirty}/>:<>
{accountPrinter?<button className="primary" disabled={pending||!valid||!name.trim()} onClick={()=>void save(cloudConnection(accountPrinter))}>{t('Add printer')}</button>:
!machine&&connect?<PrinterPanel key={template.name} inline creation={{name,type:template.connection_hint,save:async value=>save(value)}} onDirty={setConnectionDirty}/>:<>
{!machine&&<p>{t('No connection')}{' · '}{t('Export G-code')}</p>}
<div className="dialog-actions"><button className="primary" disabled={pending||!valid||(!machine&&!name.trim())} onClick={()=>void save(null)}>{t(machine?'Add profile':'Add printer')}</button></div>
</>}
@@ -83,7 +117,8 @@ function AddMachine({templates,machine,done,cancel,onDirty}:{templates:PrinterTe
</section>;
}
export function MachineLibrary({active,token,changed,editPreset,onDirty,openDevice}:{active:boolean;token:number;changed:()=>void;
export function MachineLibrary({active,token,changed,editPreset,onDirty,openDevice,bambuCloud,openBambuAccount,cloudRequest,consumeCloudRequest}:{active:boolean;token:number;changed:()=>void;
bambuCloud?:BambuCloudState|null;openBambuAccount?:()=>void;cloudRequest?:AccountPrinter;consumeCloudRequest?:()=>void;
editPreset:(machine:Machine,profile:MachineProfile,preset:MachinePreset)=>void;onDirty:(value:boolean)=>void;openDevice?:(id:string)=>void}) {
const {user}=useAuth(),canAdd=!user||user.admin||user.can_add_printers;
const [machines,setMachines]=useState<Machine[]>([]),[templates,setTemplates]=useState<PrinterTemplate[]>([]);
@@ -107,7 +142,7 @@ export function MachineLibrary({active,token,changed,editPreset,onDirty,openDevi
}
}finally{if(statusRequest.current===abort){statusRequest.current=null;setReadingStatus(false);}}
}
const [selected,setSelected]=useState(''),[adding,setAdding]=useState<false|'machine'|'profile'|'custom-machine'|'custom-profile'>(false),[name,setName]=useState('');
const [selected,setSelected]=useState(''),[adding,setAdding]=useState<false|'machine'|'cloud-machine'|'profile'|'custom-machine'|'custom-profile'>(false),[name,setName]=useState('');
const [nameBase,setNameBase]=useState({name:'',revision:0});
const [connectionReset,setConnectionReset]=useState(0);
const [managing,setManaging]=useState<{profile:string;scope?:PresetScope;preset?:string;action?:LibraryAction}|null>(null);
@@ -148,16 +183,26 @@ export function MachineLibrary({active,token,changed,editPreset,onDirty,openDevi
async function mutate(work:()=>Promise<unknown>){setPending(true);setError('');try{await work();await load();changed();}catch(reason){setError(reason);}finally{setPending(false);}}
const choose=(value:Machine)=>{if(!canLeave())return;clearDirty();setSelected(value.id);setName(value.name);setNameBase({name:value.name,revision:value.revision});setAdding(false);};
const done=(value:Machine)=>{clearDirty();setMachines(previous=>[value,...previous.filter(p=>p.id!==value.id)]);setSelected(value.id);setName(value.name);setNameBase({name:value.name,revision:value.revision});setAdding(false);changed();};
const [cloudPrinter,setCloudPrinter]=useState<AccountPrinter|undefined>();
useEffect(()=>{
if(!active||!canAdd||!cloudRequest)return;
setCloudPrinter(cloudRequest);setAdding('cloud-machine');consumeCloudRequest?.();
},[active,canAdd,cloudRequest,consumeCloudRequest]);
const managed=machine?.profiles.find(profile=>profile.id===managing?.profile);
if(machine&&managed&&canManage)return <OwnedLibraryManagement machine={machine} profile={managed} initialScope={managing?.scope} initialPreset={managing?.preset} initialAction={managing?.action} templates={templates} onDirty={markDirty}
done={value=>{done(value);setManaging(null);}} cancel={()=>{clearDirty();setManaging(null);void load().catch(setError);}}/>;
if((adding==='custom-machine'&&canAdd)||(adding==='custom-profile'&&canManage))return <OwnedPrinterWizard templates={templates} machine={adding==='custom-profile'?machine:undefined} done={done} onDirty={markDirty}
cancel={()=>{if(canLeave()){clearDirty();setAdding(false);}}}/>;
if(adding&&(adding==='profile'?canManage:canAdd))return <AddMachine templates={templates} machine={adding==='profile'?machine:undefined} done={done} onDirty={markDirty}
if(adding&&(adding==='profile'?canManage:canAdd))return <AddMachine key={adding} templates={templates} cloud={adding==='cloud-machine'} initialPrinter={adding==='cloud-machine'?cloudPrinter:undefined} machine={adding==='profile'?machine:undefined} done={done} onDirty={markDirty}
cancel={()=>{if(canLeave()){clearDirty();setAdding(false);}}}/>;
return <section className="machine-library">
<header className="machine-heading"><h1>{t('Printers')}</h1><div className="dialog-actions">
{canAdd&&<button className="primary" disabled={pending||loading||!templates.length} onClick={()=>{if(canLeave()){clearDirty();setAdding('machine');}}}>{t('Add printer')}</button>}
{canAdd&&bambuCloud&&<button disabled={pending||loading||!templates.length} onClick={()=>{
if(!canLeave())return;
if(!bambuCloud?.logged_in){openBambuAccount?.();return;}
clearDirty();setCloudPrinter(undefined);setAdding('cloud-machine');
}}>{t('Add from Bambu Lab account')}</button>}
{canAdd&&<button disabled={pending||loading||!templates.length} onClick={()=>{if(canLeave()){clearDirty();setAdding('custom-machine');}}}>{t('Create custom printer')}</button>}
<button disabled={pending||loading} onClick={()=>{if(canLeave()){clearDirty();void load(true).catch(setError);}}}>{t('Reload')}</button>
<button disabled={loading||readingStatus||!machines.some(value=>value.has_connection&&(value.access?.role!=='member'||value.access.permissions.monitor))} onClick={()=>void refreshStatus()}>{t(readingStatus?'Loading…':'Refresh status')}</button>
+6 -3
View File
@@ -72,9 +72,11 @@ export function PhysicalMaterials({printerId,revision,operation,disabled,onWorkL
async function read(quiet=false){
if(quiet&&streaming&&!live.current)return;
if(reading.current)return;reading.current=true;const controller=new AbortController();request.current=controller;if(!quiet)setBusy(true);setError('');
try{const state=await readPrinterState<MaterialState>(`${printerPath(printerId)}/filament-state?revision=${revision}${quiet?(streaming?'&observe=true':''):'&fresh=true'}`,controller.signal);
try{const [state,available]=await Promise.all([
readPrinterState<MaterialState>(`${printerPath(printerId)}/filament-state?revision=${revision}${quiet?(streaming?'&observe=true':''):'&fresh=true'}`,controller.signal),
quiet&&followFeeder?null:api<FilamentProduct[]>(`/filament-products?machine_id=${printerId}`,{signal:controller.signal}),
]);
if(state.revision!==revision)throw new Error('The printer connection changed. Reload it before reading filament state.');
const available=quiet&&followFeeder?null:await api<FilamentProduct[]>(`/filament-products?machine_id=${printerId}`,{signal:controller.signal});
if(!controller.signal.aborted){
setView(state);if(available)setProducts(available);setStale(false);setOffline(false);
const command=operation.filament as {source?:string;operation?:string;box_id?:number;material_id?:number;material?:string;color?:string;minimum?:number;maximum?:number}|undefined;
@@ -178,7 +180,8 @@ export function PhysicalMaterials({printerId,revision,operation,disabled,onWorkL
return <article key={key} className="device-material-slot" data-active={slot.active}>
<strong>{t(slot.name)}</strong>
<div className="device-material-heading">
<SlotColorPicker color={slot.color} disabled={locked||!slot.operations.includes('set_material')||slot.editable_fields?.includes('color')===false||!slot.material.trim()} title={slot.material.trim()?t('Change slot color'):t('Set the slot material first')} label={`${t('Change slot color')} · ${module.name} · ${slot.name}`}
{slot.identity?.rgba?.endsWith('00')&&slot.material&&<span className="transparent-filament">{t('Transparent')}</span>}
<SlotColorPicker color={slot.color} transparent={slot.identity?.rgba?.endsWith('00')} disabled={locked||!slot.operations.includes('set_material')||slot.editable_fields?.includes('color')===false||!slot.material.trim()} title={slot.material.trim()?t('Change slot color'):t('Set the slot material first')} label={`${t('Change slot color')} · ${module.name} · ${slot.name}`}
commit={value=>void send({source:'physical',operation:'set_material',box_id:slot.box_id,material_id:slot.material_id,material:slot.material,color:value})}/>
<button type="button" disabled={locked||!slot.operations.includes('set_material')||slot.editable_fields?.includes('material')===false} aria-label={`${t('Change slot material')} · ${module.name} · ${slot.name}`} title={t(slot.editable_fields?.includes('material')===false?'Choose a filament product to change the material':'Change slot material')}
onClick={()=>{setEdit(editing?'':key);setMaterial(slot.material);}}>{slot.material||t('Unknown')}</button>
+18 -8
View File
@@ -7,7 +7,7 @@ import {connectionDraft,printerPath,uploadMethods,startMethods,usablePrinterAgen
import {RemoteConnectionOptions,AdvancedConnectionOptions,type DeviceAgentChoice} from './ConnectionOptions';
import {PrinterPairing,PendingPairings,pendingPairingId,isPendingPairing,type Pairing} from './PrinterPairing';
import {PrinterAgentDiscovery} from './PrinterAgentDiscovery';
import {BambuCloudConnection,isCloudDraft} from './BambuCloudConnection';
import {BambuCloudConnection,CLOUD_HOST,CLOUD_TYPE,isCloudDraft} from './BambuCloudConnection';
import {machineConnection,machinePath,type Machine} from './machines';
interface DiscoveredHost {name:string;host:string;flashforge_serial_number?:string;bambu_serial_number?:string;printer_model?:string;}
@@ -39,6 +39,13 @@ export function PrinterPanel({inline=false,active=true,machineId,creation,onChan
useEffect(()=>()=>dirtyCallback.current?.(false),[]);
const spec=types.find(value=>value.id===draft.type);
const cloudBambu=isCloudDraft(draft);
const [cloudState,setCloudState]=useState<{available:boolean;logged_in?:boolean}|null>(null);
useEffect(()=>{
if(!active)return;
const controller=new AbortController();
void api<{available:boolean;logged_in?:boolean}>('/bambu-cloud',{signal:controller.signal}).then(setCloudState).catch(()=>{});
return()=>controller.abort();
},[active]);
const showDeviceKey=!cloudBambu&&!!spec?.auth_types.includes('api_key')&&(draft.auth_type!=='digest'||!!spec.api_key_with_digest);
const reference=draft.plugin_agent as PluginAgentReference|null;
const agent=agents.find(value=>value.plugin===reference?.id&&value.capability===reference?.capability);
@@ -81,11 +88,12 @@ export function PrinterPanel({inline=false,active=true,machineId,creation,onChan
}
useEffect(()=>{if(inline&&active&&(!printer||machineId&&machineId!==identity))void action(()=>load(machineId??identity));},[inline,active,machineId]);
const discard=()=>!dirty||window.confirm(t('Discard unsaved changes?'));
function chooseType(type:string){
function chooseType(selection:string){
const cloud=selection===CLOUD_TYPE,type=cloud?'bambu_lan':selection;
const next=types.find(value=>value.id===type);
setDraft(previous=>({...previous,type,auth_type:next?.auth_types.includes(String(previous.auth_type))?previous.auth_type:next?.auth_types[0],
setDraft(previous=>({...previous,type,host:cloud?CLOUD_HOST:isCloudDraft(previous)?'':previous.host,auth_type:next?.auth_types.includes(String(previous.auth_type))?previous.auth_type:next?.auth_types[0],
device_agent:'',plugin_agent:null,printer_slug:'',model_group:'#',console_host:'',console_port:null,
websocket_url:'',bambu_serial_number:'',bambu_transport:'lan',flashforge_serial_number:'',printer_model:'',simplyprint_panel_url:'',camera_origins:[],
websocket_url:'',bambu_serial_number:'',bambu_transport:cloud?'cloud':'lan',flashforge_serial_number:'',printer_model:'',simplyprint_panel_url:'',camera_origins:[],
upload_timeout_seconds:null}));setDiscovered([]);setSearched(false);setMessage('');
}
function chooseAgent(value:string){
@@ -140,7 +148,7 @@ export function PrinterPanel({inline=false,active=true,machineId,creation,onChan
{saveRecovery&&<p className="connection-description" aria-live="polite">{t(saveRecovery==='conflict'?'This connection was changed elsewhere. Your changes were not saved. Load saved settings before editing again.':'The save result is unknown. Load saved settings to check the server before saving again. Your form changes are preserved until then.')}</p>}
{message&&<p role="status">{message}</p>}
{pairingActive&&<p>{t('Finish or cancel device pairing before editing or deleting this connection.')}</p>}
<form onSubmit={event=>{event.preventDefault();if(!printer||busy||saveRecovery)return;void action(async()=>{
<form onSubmit={event=>{event.preventDefault();if(!printer||busy||saveRecovery||cloudBambu&&(!cloudState?.logged_in||!draft.bambu_serial_number))return;void action(async()=>{
const payload=connectionPayload();
if(creation){await creation.save({...payload,name:creation.name});return;}
let value:PrinterConnection;
@@ -154,10 +162,12 @@ export function PrinterPanel({inline=false,active=true,machineId,creation,onChan
});}}>
<fieldset disabled={busy||!printer||pairingActive}>
{!machineId&&!creation&&input('name','Nazwa drukarki',{required:true,max:128})}
<label>{t('Host type')}<select required value={String(draft.type??'')} onChange={event=>chooseType(event.target.value)}>
<label>{t('Host type')}<select required value={cloudBambu?CLOUD_TYPE:String(draft.type??'')} onChange={event=>chooseType(event.target.value)}>
<option disabled value="">{t('Select')}</option>{types.map(value=><option key={value.id} value={value.id}>{value.name}</option>)}
{types.some(value=>value.id==='bambu_lan')&&<option value={CLOUD_TYPE}>{t('Bambu Lab cloud')}</option>}
</select></label>
{draft.type==='bambu_lan'&&<BambuCloudConnection draft={draft} field={field}/>}
{cloudBambu&&cloudState?.available===false&&<p>{t('Bambu Lab cloud requires a cloud-enabled build.')}</p>}
{cloudBambu&&cloudState?.available!==false&&<BambuCloudConnection draft={draft} field={field} signedIn={Boolean(cloudState?.logged_in)}/>}
{!cloudBambu&&input('host','Adres serwera druku',{required:true})}
{!cloudBambu&&<label>{t('Authentication')}<select value={String(draft.auth_type??'')} onChange={event=>field('auth_type',event.target.value)}>
{(spec?.auth_types??[]).map(value=><option key={value} value={value}>{t(value==='api_key'?(spec?.api_key_label??'API key'):{none:'None',basic:'Basic authentication',digest:'Digest authentication'}[value]??value)}</option>)}
@@ -233,7 +243,7 @@ export function PrinterPanel({inline=false,active=true,machineId,creation,onChan
</>}
</section>}
{spec&&printer&&<AdvancedConnectionOptions key={`advanced:${identity}:${printer.revision}:${spec.id}`} printer={printer} spec={spec} draft={draft} field={field}/>}
<div className="connection-form-actions"><button type="submit" className="primary" disabled={!!saveRecovery||(!creation&&!dirty)||!spec||(draft.type==='plugin'&&!validAgent)}>{t(creation?'Add printer':'Zapisz połączenie')}</button></div>
<div className="connection-form-actions"><button type="submit" className="primary" disabled={!!saveRecovery||(!creation&&!dirty)||!spec||(cloudBambu&&(!cloudState?.logged_in||!draft.bambu_serial_number))||(draft.type==='plugin'&&!validAgent)}>{t(creation?'Add printer':'Zapisz połączenie')}</button></div>
</fieldset>
</form>
{draft.type==='plugin'&&agent&&<PrinterAgentDiscovery key={`${identity}:${agent.plugin}:${agent.capability}`} agent={agent} active={active} busy={busy||pairingActive} onBusy={setBusy} refresh={refreshAgents}
+5 -1
View File
@@ -23,7 +23,7 @@ const label=(item:{name:string;payload?:{display_name?:string}})=>item.payload?.
const receiptKey='orca-preset-bundle-review';
function remember(id:string|null,body:Commit|null=null){try{if(id)localStorage.setItem(receiptKey,JSON.stringify({id,body}));else localStorage.removeItem(receiptKey);}catch{/* Server pending imports also recover uploads without browser storage. */}}
export function ProfileBundles({close,changed,schema={},openAccount}:{close:()=>void;changed:()=>void;schema?:Record<string,Option>;openAccount?:()=>void}){
export function ProfileBundles({close,changed,schema={},openAccount,bambuCloud}:{close:()=>void;changed:()=>void;schema?:Record<string,Option>;openAccount?:()=>void;bambuCloud?:boolean}){
const dialog=useRef<HTMLDialogElement>(null),request=useRef<AbortController|null>(null),lock=useRef(false),mounted=useRef(true);
const [tab,setTab]=useState<'import'|'export'|'installed'|'cloud'>('import'),[childBusy,setChildBusy]=useState(false),[busy,setBusy]=useState(false),[error,setError]=useState<unknown>(null),[message,setMessage]=useState('');
const [file,setFile]=useState<File|null>(null),[preserve,setPreserve]=useState(true),[replace,setReplace]=useState(false);
@@ -109,6 +109,10 @@ export function ProfileBundles({close,changed,schema={},openAccount}:{close:()=>
<label>{t('File')}<FileInput accept=".json,.zip,.orca_printer,.orca_filament,.orca_bundle" aria-label={t('Import Configs')} onChange={event=>setFile(event.currentTarget.files?.[0]??null)}/></label>
<label><input type="checkbox" checked={preserve} onChange={event=>{setPreserve(event.target.checked);if(!event.target.checked)setReplace(false);}}/>{t('Preserve package identities')}</label>
<label title={!preserve?t('Preserve package identities before replacing a package.'):undefined}><input type="checkbox" disabled={!preserve} checked={replace} onChange={event=>setReplace(event.target.checked)}/>{t('Replace complete packages (review removed presets before import)')}</label>
{bambuCloud&&<button disabled={plan?.status==='pending'} onClick={()=>void action(async()=>{
review(await api<Plan>('/user-profile-imports/bambu-cloud',jsonRequest('POST',{})));
await load();
})}>{t('Fetch presets from Bambu Lab')}</button>}
<button disabled={!file||!!plan&&plan.status==='pending'} onClick={()=>void action(stage)}>{t('Review import')}</button>
</fieldset>
<section aria-label={t('Pending imports')}><h3>{t('Pending imports')}</h3><button disabled={busy} onClick={()=>void action(load)}>{t('Refresh')}</button>
+6 -4
View File
@@ -29,14 +29,16 @@ export function ProjectPhysicalFilament({machine,profileId,presetId,products,dis
return <div className="project-physical-filament">
{source&&<><small>{t('Printer slot')}{' · '}{t('Module')}{' '}{source.box_id}{' · '}{t('Slot')}{' '}{source.material_id+1}</small><button type="button" disabled={disabled||busy} onClick={()=>choose(presetId,null)}>{t('Use without printer slot')}</button></>}
{canRead&&<button type="button" disabled={disabled||busy} onClick={()=>view?setView(null):void read()}>{t(view?'Close printer slots':'Choose from printer')}</button>}
{busy&&<span role="status">{t('Reading printer filaments…')}</span>}
{busy&&<span role="status">{t(view?'Checking the slot assignment…':'Reading printer filaments…')}</span>}
{busy&&!view&&<button type="button" onClick={()=>{request.current?.abort();setBusy(false);}}>{t('Cancel')}</button>}
{error&&<p role="alert">{error}</p>}
{view&&<ul aria-label={t('Printer filament slots')}>{view.slots.map(slot=>{
const product=products.find(p=>p.id===slot.product?.id),profiles=product?.profiles.filter(p=>p.profile_id===profileId)??[];
const product=products.find(p=>p.id===slot.product?.id),profiles=product?.profiles.filter(p=>p.machine_id===machine.id&&p.profile_id===profileId)??[];
const preferred=profiles.filter(p=>p.preferred),automatic=profiles.length===1?profiles[0]:preferred.length===1?preferred[0]:undefined;
const rgba=slot.identity?.rgba;
const key=`${slot.box_id}:${slot.material_id}`,preset=tuning[key]??automatic?.preset_id;
return <li key={key}><span className="product-swatch" style={{backgroundColor:slot.color}}/><strong>{view.modules.find(module=>module.id===slot.box_id)?.name}{' · '}{slot.name}{' · '}{slot.product?.name??slot.material}</strong>
{slot.assignment_state!=='assigned'?<small>{t('Assign and confirm a filament product in Device first.')}</small>:!profiles.length?<small>{t('Add compatible slicing settings for this printer preset in the filament library.')}</small>:<>
return <li key={key}><span className="product-swatch" style={{backgroundColor:rgba?'#'+rgba:slot.color}}/><strong>{view.modules.find(module=>module.id===slot.box_id)?.name}{' · '}{slot.name}{' · '}{slot.product?.name??slot.material}</strong>{rgba?.endsWith('00')&&slot.material&&<small>{t('Transparent')}</small>}
{slot.assignment_state!=='assigned'?<small>{t('In Device, assign a filament from your library to this AMS slot and confirm it. AMS reports the loaded material but does not provide slicing settings.')}</small>:!profiles.length?<small>{t('In Filament library, add a slicing profile for this printer and nozzle. You can use an imported Bambu Lab preset.')}</small>:<>
{profiles.length>1&&<label>{t('Slicing profile')}<select aria-label={`${t('Slicing profile')} · ${slot.name}`} disabled={busy} value={preset??''} onChange={e=>setTuning(v=>({...v,[key]:e.target.value}))}><option value="" disabled>{t('Select')}</option>{profiles.map(p=><option key={p.preset_id} value={p.preset_id}>{p.label}</option>)}</select></label>}
<button type="button" disabled={disabled||busy||!preset||!slot.assignment_revision} onClick={()=>void useSlot(slot.box_id,slot.material_id,slot.assignment_revision!,preset)}>{t('Use this filament')}</button>
</>}
+2 -2
View File
@@ -1,7 +1,7 @@
import {useEffect,useRef} from 'react';
/** Native change commits the picker; input previews must never send commands. */
export function SlotColorPicker({color,disabled,label,title,commit}:{color:string;disabled:boolean;label:string;title?:string;commit:(color:string)=>void}){
export function SlotColorPicker({color,transparent,disabled,label,title,commit}:{color:string;transparent?:boolean;disabled:boolean;label:string;title?:string;commit:(color:string)=>void}){
const input=useRef<HTMLInputElement>(null),pending=useRef(false);
const latest=useRef({color,disabled,commit});latest.current={color,disabled,commit};
useEffect(()=>{if(input.current)input.current.value=color;pending.current=disabled;},[color,disabled]);
@@ -14,5 +14,5 @@ export function SlotColorPicker({color,disabled,label,title,commit}:{color:strin
};
element.addEventListener('change',changed);return()=>element.removeEventListener('change',changed);
},[]);
return <input ref={input} type="color" className="device-slot-color-picker" defaultValue={color} disabled={disabled} aria-label={label} title={title??label}/>;
return <input ref={input} type="color" className="device-slot-color-picker" data-transparent={transparent||undefined} defaultValue={color} disabled={disabled} aria-label={label} title={title??label}/>;
}
+21 -12
View File
@@ -1,23 +1,32 @@
import {useSyncExternalStore} from 'react';
import {t} from './i18n';
type Theme = 'dark' | 'light';
type Theme = 'system' | 'dark' | 'light';
const storageKey='orca-theme';
const systemTheme=window.matchMedia('(prefers-color-scheme: dark)');
const listeners=new Set<()=>void>();
let theme:Theme='dark';
try {theme=localStorage.getItem('orca-theme')==='light'?'light':'dark';} catch { /* Storage is optional. */ }
function apply(value:Theme) {
theme=value;document.documentElement.dataset.theme=value;
const readTheme=(value:string|null):Theme=>value==='light'||value==='dark'?value:'system';
let theme:Theme='system';
try {theme=readTheme(localStorage.getItem(storageKey));} catch { /* Storage is optional. */ }
function apply(){
document.documentElement.dataset.theme=theme==='system'?(systemTheme.matches?'dark':'light'):theme;
}
function choose(value:Theme){
theme=value;apply();
for(const listener of listeners)listener();
}
apply(theme);
apply();
systemTheme.addEventListener('change',()=>{if(theme==='system')apply();});
window.addEventListener('storage',event=>{
if(event.key==='orca-theme')apply(event.newValue==='light'?'light':'dark');
if(event.key===storageKey||event.key===null)choose(readTheme(event.newValue));
});
export function ThemeSelector() {
export function ThemeSelector(){
const value=useSyncExternalStore(listener=>{listeners.add(listener);return()=>{listeners.delete(listener);};},()=>theme);
return <label className="theme-selector">{t('Theme')}<select value={value} aria-label={t('Theme')} onChange={event=>{
const next=event.target.value as Theme;
try {localStorage.setItem('orca-theme',next);} catch { /* Retain the in-memory choice. */ }
apply(next);
}}><option value="dark">{t('Dark')}</option><option value="light">{t('Light')}</option></select></label>;
const next=readTheme(event.target.value);
try {localStorage.setItem(storageKey,next);} catch { /* Retain the in-memory choice. */ }
choose(next);
}}><option value="system">{t('System theme')}</option><option value="light">{t('Light')}</option><option value="dark">{t('Dark')}</option></select></label>;
}
+10
View File
@@ -6,3 +6,13 @@
.about-license{outline-offset:3px}.about-license pre{max-height:320px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;padding:12px;background:var(--wb-bg);border-radius:8px}.about-warning{border-left:3px solid var(--wb-warning,#d4b85b);padding-left:12px}
.about-dialog .upstream-release,.upstream-release-latest{display:grid;gap:16px;min-width:0}.about-dialog .upstream-release>*{margin:0}.upstream-release a{color:var(--wb-accent);overflow-wrap:anywhere}
@media(max-width:700px){.about-dialog{padding:16px}.about-versions{grid-template-columns:minmax(0,1fr);gap:8px}.about-versions dd{margin-bottom:8px}}
.bambu-account-dialog[open]{display:grid;align-content:start;gap:16px}
.bambu-account-dialog>*,.bambu-account-dialog section>*{margin:0}
.bambu-account-dialog section,.bambu-pairing-fields{display:grid;gap:12px;min-width:0}
.bambu-account-dialog .bambu-account-muted{color:var(--wb-muted)}
.bambu-account-dialog .about-actions{gap:12px;align-items:center}
.bambu-account-dialog .about-actions a{display:inline-flex;align-items:center;padding:8px 14px;text-decoration:none;box-sizing:border-box}
.bambu-account-dialog .bambu-pairing-fields{border-top:1px solid var(--wb-border);padding-top:12px}
.bambu-account-dialog section>button,.bambu-account-dialog li>button,.bambu-account-dialog>button{justify-self:start}
.bambu-account-dialog label:has(> input:is([type=checkbox],[type=radio])){display:flex;align-items:center;gap:8px}
+85
View File
@@ -0,0 +1,85 @@
import {api} from './api';
import {t} from './i18n';
import type {ImportTask} from './Imports';
const protocol='web-slicer.open-model.v1';
const maxBytes=512*1024*1024;
const supported=/\.(3mf|stl|step|stp)$/i;
function launchParams(){
return new URLSearchParams(window.location.hash.slice(1));
}
export function hasExternalModelLaunch(){
const params=launchParams();
return params.has('open-model')||params.has('open-model-from')||
new URLSearchParams(window.location.search).has('import-job');
}
function webURL(value:string){
const url=new URL(value);
if(!['http:','https:'].includes(url.protocol)||url.username||url.password)throw Error(t('Invalid model URL.'));
return url;
}
async function modelFromURL(value:string,filename:string|null,signal:AbortSignal){
const url=webURL(value);
const name=filename??decodeURIComponent(url.pathname.slice(url.pathname.lastIndexOf('/')+1));
if(!supported.test(name)||/[\\/\u0000-\u001f]/.test(name))throw Error(t('Choose a 3MF, STL or STEP model.'));
const response=await fetch(url,{credentials:'omit',referrerPolicy:'no-referrer',signal});
if(!response.ok||!response.body)throw Error(t('Could not download the external model.'));
if(Number(response.headers.get('Content-Length'))>maxBytes)throw Error(t('The model exceeds the 512 MiB limit.'));
const chunks:Uint8Array<ArrayBuffer>[]=[];
const reader=response.body.getReader();
let size=0;
try{
for(;;){
const {done,value:chunk}=await reader.read();
if(done)break;
size+=chunk.byteLength;
if(size>maxBytes)throw Error(t('The model exceeds the 512 MiB limit.'));
chunks.push(chunk);
}
}finally{await reader.cancel().catch(()=>{});}
return new File(chunks,name);
}
export function receiveExternalModel(receive:(file:File)=>Promise<void>,failed:(reason:unknown)=>void){
const params=launchParams();
const source=params.get('open-model-from'),url=params.get('open-model');
if(!source&&!url)return;
const abort=new AbortController();
let dispose=()=>{};
if(source){
const opener=window.opener;
try{
const origin=webURL(source).origin;
const token=params.get('request');
if(!opener||!token||!/^[a-f0-9]{32}$/.test(token))throw Error(t('The external model connection was lost.'));
let received=false;
const announce=()=>opener.postMessage({protocol,type:'ready',request:token},origin);
const timer=window.setInterval(announce,1000);
const listener=(event:MessageEvent)=>{
const data=event.data;
if(received||event.source!==opener||event.origin!==origin||data?.protocol!==protocol||
data.type!=='file'||data.request!==token||!(data.file instanceof File))return;
received=true;window.clearInterval(timer);
void receive(data.file).then(()=>opener.postMessage({protocol,type:'accepted',request:token},origin))
.catch(reason=>{failed(reason);opener.postMessage({protocol,type:'failed',request:token},origin);});
};
window.addEventListener('message',listener);
dispose=()=>{window.clearInterval(timer);window.removeEventListener('message',listener);};
announce();
}catch(reason){failed(reason);}
}else if(url){
const signal=AbortSignal.any([abort.signal,AbortSignal.timeout(120_000)]);
void modelFromURL(url,params.get('filename'),signal).then(receive).catch(reason=>{if(!abort.signal.aborted)failed(reason);});
}
return ()=>{abort.abort();dispose();};
}
export function uploadExternalModel(file:File,signal?:AbortSignal){
if(!supported.test(file.name))throw Error(t('Choose a 3MF, STL or STEP model.'));
if(file.size>maxBytes)throw Error(t('The model exceeds the 512 MiB limit.'));
const data=new FormData();data.set('file',file);
return api<ImportTask>('/imports/open-model',{method:'POST',body:data,signal});
}
+32 -1
View File
@@ -13,7 +13,8 @@
.product-library-detail h2,.product-library-detail h3{margin:0}
.product-metadata-form,.product-profile-form,.product-availability,.product-library-administration form,.product-save-recovery{display:grid;gap:16px;min-width:0}
.product-metadata-form fieldset,.product-library-administration fieldset{display:grid;gap:16px;margin:0;padding:0;border:0;min-width:0}
.product-metadata-form fieldset{grid-template-columns:repeat(2,minmax(0,1fr))}.product-notes{grid-column:1/-1}
.product-metadata-form fieldset{grid-template-columns:repeat(2,minmax(0,1fr))}.product-notes,.product-template-wizard{grid-column:1/-1}
.product-availability,.product-slicing-profiles,.product-library-administration{border-top:1px solid var(--wb-border);padding-top:20px;min-width:0}
.product-slicing-profiles[open]>summary,.product-library-administration[open]>summary{margin-bottom:20px}
.product-slicing-profiles ul{list-style:none;padding:0;margin:0 0 20px;display:grid;gap:16px}.product-slicing-profiles li{display:grid;gap:12px;padding:16px;border:1px solid var(--wb-border);border-radius:8px;min-width:0}
@@ -24,3 +25,33 @@
.filament-product-library input[type=color]{width:72px;height:36px;padding:4px;cursor:pointer}
.filament-product-library input[type=color]::-webkit-color-swatch-wrapper{padding:0}
.filament-product-library input[type=color]::-webkit-color-swatch{border:0;border-radius:3px}
.filament-preset-browser{
width:min(900px,calc(100% - 32px));max-height:calc(100dvh - 32px);box-sizing:border-box;
padding:0;border:1px solid var(--wb-border);border-radius:16px;
background:var(--wb-panel);color:inherit;overflow:hidden;
}
.filament-preset-browser[open]{display:flex;flex-direction:column}
.filament-preset-browser::backdrop{background:rgb(0 0 0 / .54)}
.filament-browser-header,.filament-browser-footer{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;padding:16px 24px}
.filament-browser-header{border-bottom:1px solid var(--wb-border)}
.filament-browser-header h2,.filament-browser-header p{margin:0}
.filament-browser-header p{margin-top:4px;color:var(--wb-muted)}
.filament-browser-body{overflow:auto;min-height:0;padding:20px 24px}
.filament-browser-controls{display:grid;gap:14px;min-width:0;margin:0;padding:0;border:0}
.filament-browser-controls input,.filament-browser-controls select,.filament-browser-selection select{width:100%;min-width:0;box-sizing:border-box}
.filament-browser-chips{display:flex;flex-wrap:wrap;gap:8px}
.filament-browser-chips button{border-radius:999px;padding-inline:14px}
.filament-browser-chips button[aria-pressed=true],.filament-browser-results button[aria-pressed=true]{border-color:var(--wb-accent);background:var(--wb-selected)}
.filament-browser-filters,.filament-browser-results{display:grid;gap:10px;grid-template-columns:repeat(auto-fit,minmax(min(100%,215px),1fr))}
.filament-browser-results button{display:grid;align-content:start;text-align:start;white-space:normal;overflow-wrap:anywhere;gap:4px;padding:12px;min-height:62px}
.filament-browser-results span,.filament-browser-empty{color:var(--wb-muted)}
.filament-browser-empty{border:1px dashed var(--wb-border);border-radius:10px;padding:20px;margin:0}
.filament-browser-more{margin-top:10px}
.filament-browser-footer{border-top:1px solid var(--wb-border)}
.filament-browser-footer .printer-actions{margin-inline-start:auto}
.filament-browser-selection{flex:1 1 260px;min-width:0;display:grid;gap:6px;overflow-wrap:anywhere}
@media(max-width:600px){
.filament-preset-browser{width:calc(100% - 16px);max-height:calc(100dvh - 16px)}
.filament-browser-header,.filament-browser-footer,.filament-browser-body{padding:12px}
}
+228
View File
@@ -8694,5 +8694,233 @@
"Prints from the external spool; AMS mapping is not supported yet. Printers that verify commands also need a slicer key (see below).": {
"en": "Prints from the external spool; AMS mapping is not supported yet. Printers that verify commands also need a slicer key (see below).",
"pl": "Druk z zewnętrznej szpuli; mapowanie AMS nie jest jeszcze obsługiwane. Drukarki weryfikujące komendy wymagają też klucza slicera (patrz niżej)."
},
"Bambu Lab cloud": {
"en": "Bambu Lab cloud",
"pl": "Chmura Bambu Lab"
},
"Bambu Lab cloud requires a cloud-enabled build.": {
"en": "Bambu Lab cloud requires a cloud-enabled build.",
"pl": "Chmura Bambu Lab wymaga wersji aplikacji z obsługą chmury."
},
"Add from Bambu Lab account": {
"en": "Add from Bambu Lab account",
"pl": "Dodaj z konta Bambu Lab"
},
"Add to printers": {
"en": "Add to printers",
"pl": "Dodaj do drukarek"
},
"Choose the model and nozzle preset for this cloud printer.": {
"en": "Choose the model and nozzle preset for this cloud printer.",
"pl": "Wybierz model i preset dyszy dla tej drukarki chmurowej."
},
"Import Bambu Lab presets": {
"en": "Import Bambu Lab presets",
"pl": "Importuj presety Bambu Lab"
},
"Fetch presets from Bambu Lab": {
"en": "Fetch presets from Bambu Lab",
"pl": "Pobierz presety z Bambu Lab"
},
"Start from a filament preset": {
"en": "Start from a filament preset",
"pl": "Zacznij od presetu filamentu"
},
"Close template picker": {
"en": "Close template picker",
"pl": "Zamknij wybór presetu"
},
"Search presets": {
"en": "Search presets",
"pl": "Szukaj presetów"
},
"Replace the filament draft with this preset?": {
"en": "Replace the filament draft with this preset?",
"pl": "Zastąpić robocze dane filamentu tym presetem?"
},
"The preset fills in the filament details. Add slicing settings for a printer after saving.": {
"en": "The preset fills in the filament details. Add slicing settings for a printer after saving.",
"pl": "Preset uzupełni dane filamentu. Ustawienia cięcia dla drukarki możesz dodać po zapisaniu."
},
"Transparent": {
"en": "Transparent",
"pl": "Przezroczysty"
},
"Checking the slot assignment…": {
"en": "Checking the slot assignment…",
"pl": "Sprawdzanie przypisania slotu…"
},
"In Device, assign a filament from your library to this AMS slot and confirm it. AMS reports the loaded material but does not provide slicing settings.": {
"en": "In Device, assign a filament from your library to this AMS slot and confirm it. AMS reports the loaded material but does not provide slicing settings.",
"pl": "W panelu urządzenia przypisz filament z biblioteki do tego slotu AMS i potwierdź przypisanie. AMS podaje dane załadowanego materiału. Ustawienia cięcia pochodzą z presetu."
},
"In Filament library, add a slicing profile for this printer and nozzle. You can use an imported Bambu Lab preset.": {
"en": "In Filament library, add a slicing profile for this printer and nozzle. You can use an imported Bambu Lab preset.",
"pl": "W bibliotece filamentów dodaj profil cięcia dla tej drukarki i dyszy. Możesz użyć zaimportowanego presetu Bambu Lab."
},
"Choose filament preset": {
"en": "Choose filament preset",
"pl": "Wybierz preset filamentu"
},
"Choose a material type": {
"en": "Choose a material type",
"pl": "Wybierz rodzaj materiału"
},
"Choose a manufacturer": {
"en": "Choose a manufacturer",
"pl": "Wybierz producenta"
},
"All manufacturers": {
"en": "All manufacturers",
"pl": "Wszyscy producenci"
},
"Use preset": {
"en": "Use preset",
"pl": "Użyj presetu"
},
"Find a filament to fill in its library details.": {
"en": "Find a filament to fill in its library details.",
"pl": "Znajdź filament, aby uzupełnić jego dane w bibliotece."
},
"Loading filament presets…": {
"en": "Loading filament presets…",
"pl": "Wczytywanie presetów filamentu…"
},
"e.g. Bambu PLA or PETG HF": {
"en": "e.g. Bambu PLA or PETG HF",
"pl": "np. Bambu PLA lub PETG HF"
},
"Popular materials": {
"en": "Popular materials",
"pl": "Popularne materiały"
},
"All materials": {
"en": "All materials",
"pl": "Wszystkie materiały"
},
"Search by name or choose a material to browse presets.": {
"en": "Search by name or choose a material to browse presets.",
"pl": "Wyszukaj nazwę lub wybierz materiał, aby przejrzeć presety."
},
"Preset variant": {
"en": "Preset variant",
"pl": "Wariant presetu"
},
"Choose a variant": {
"en": "Choose a variant",
"pl": "Wybierz wariant"
},
"Enter details manually": {
"en": "Enter details manually",
"pl": "Wprowadź dane ręcznie"
},
"System theme": {
"en": "System theme",
"pl": "Systemowy"
},
"Preset synchronization": {
"en": "Preset synchronization",
"pl": "Synchronizacja presetów"
},
"Sync Bambu Lab presets automatically": {
"en": "Sync Bambu Lab presets automatically",
"pl": "Automatycznie synchronizuj presety Bambu Lab"
},
"Synchronizing presets…": {
"en": "Synchronizing presets…",
"pl": "Synchronizowanie presetów…"
},
"Preset sync failed. It will retry automatically.": {
"en": "Preset sync failed. It will retry automatically.",
"pl": "Synchronizacja presetów nie powiodła się. Aplikacja spróbuje ponownie."
},
"Last synchronized: {time}": {
"en": "Last synchronized: {time}",
"pl": "Ostatnia synchronizacja: {time}"
},
"Waiting for the first synchronization.": {
"en": "Waiting for the first synchronization.",
"pl": "Oczekiwanie na pierwszą synchronizację."
},
"Presets needing review: {count}": {
"en": "Presets needing review: {count}",
"pl": "Presety do sprawdzenia: {count}"
},
"Sync now": {
"en": "Sync now",
"pl": "Synchronizuj teraz"
},
"Opening external model…": {
"en": "Opening external model…",
"pl": "Otwieranie modelu z zewnętrznego źródła…"
},
"Invalid model URL.": {
"en": "Invalid model URL.",
"pl": "Nieprawidłowy adres modelu."
},
"Choose a 3MF, STL or STEP model.": {
"en": "Choose a 3MF, STL or STEP model.",
"pl": "Wybierz model 3MF, STL lub STEP."
},
"Could not download the external model.": {
"en": "Could not download the external model.",
"pl": "Nie udało się pobrać modelu z zewnętrznego źródła."
},
"The model exceeds the 512 MiB limit.": {
"en": "The model exceeds the 512 MiB limit.",
"pl": "Model przekracza limit 512 MiB."
},
"The external model connection was lost.": {
"en": "The external model connection was lost.",
"pl": "Utracono połączenie z kartą przekazującą model."
},
"Choose a physical printer in Web Slicer before opening external models": {
"en": "Choose a physical printer in Web Slicer before opening external models",
"pl": "Przed otwarciem modeli zewnętrznych wybierz drukarkę w Web Slicerze"
},
"Choose a printer profile before opening external models": {
"en": "Choose a printer profile before opening external models",
"pl": "Przed otwarciem modeli zewnętrznych wybierz profil drukarki"
},
"Sign in with the desktop helper": {
"en": "Sign in with the desktop helper",
"pl": "Zaloguj przez aplikację pomocniczą"
},
"Desktop pairing link": {
"en": "Desktop pairing link",
"pl": "Link parowania z komputerem"
},
"Paste this link into the Web Slicer desktop helper. It expires after 10 minutes.": {
"en": "Paste this link into the Web Slicer desktop helper. It expires after 10 minutes.",
"pl": "Wklej ten link w aplikacji pomocniczej Web Slicer. Wygasa po 10 minutach."
},
"Use the HTTPS Web Slicer address to pair the desktop helper": {
"en": "Use the HTTPS Web Slicer address to pair the desktop helper",
"pl": "Aby sparować aplikację pomocniczą, otwórz adres HTTPS Web Slicera"
},
"Your Bambu Lab connection is private to your Web Slicer account. Automatic sync to the shared preset library is disabled.": {
"en": "Your Bambu Lab connection is private to your Web Slicer account. Automatic sync to the shared preset library is disabled.",
"pl": "Połączenie z Bambu Lab jest prywatne dla Twojego konta Web Slicer. Automatyczna synchronizacja ze wspólną biblioteką presetów jest wyłączona."
},
"Desktop helper": {
"en": "Desktop helper",
"pl": "Aplikacja pomocnicza"
},
"Download {platform}": {
"en": "Download {platform}",
"pl": "Pobierz {platform}"
},
"Download the helper, then create a pairing link and paste it into the app.": {
"en": "Download the helper, then create a pairing link and paste it into the app.",
"pl": "Pobierz aplikację pomocniczą, utwórz link parowania i wklej go w aplikacji."
},
"The desktop helper packages are unavailable on this server.": {
"en": "The desktop helper packages are unavailable on this server.",
"pl": "Paczki aplikacji pomocniczej są niedostępne na tym serwerze."
},
"Create pairing link": {
"en": "Create pairing link",
"pl": "Utwórz link parowania"
}
}
+45 -5
View File
@@ -16,6 +16,7 @@ import {GcodeViewer} from './GcodeViewer';
import {Troubleshooting} from './Troubleshooting';
import {RecentProjects} from './RecentProjects';
import {Imports,type ImportRequest,type ImportTask} from './Imports';
import {hasExternalModelLaunch,receiveExternalModel,uploadExternalModel} from './externalModel';
import {BrowserPreferences} from './BrowserPreferences';
import {useShortcut} from './shortcuts';
import {ShortcutList} from './ShortcutList';
@@ -37,6 +38,7 @@ import {HelpCenter} from './HelpCenter';
import {ThreeMFPreferences} from './ThreeMFImport';
import {ProfileBundles} from './ProfileBundles';
import {CloudAccount} from './CloudAccount';
import type {AccountPrinter} from './BambuCloudConnection';
import {BambuCloudAccount,type BambuCloudState} from './BambuCloudAccount';
import {AuthBoundary,LocalAccount,useAuth} from './LocalAccount';
import {UsersPage} from './UsersPage';
@@ -226,6 +228,7 @@ function App() {
const [aboutOpen,setAboutOpen]=useState(false);
const [profileBundleTools,setProfileBundleTools]=useState(false),[profileBundlesOpen,setProfileBundlesOpen]=useState(false);
const [cloudAccountOpen,setCloudAccountOpen]=useState(false);
const [cloudPrinterRequest,setCloudPrinterRequest]=useState<AccountPrinter>();
const [bambuCloud,setBambuCloud]=useState<BambuCloudState|null>(null),[bambuCloudOpen,setBambuCloudOpen]=useState(false);
// Optional Bambu account (cloud sideload build only); the native sign-in screen
// announces a change when it returns to the web client.
@@ -233,6 +236,20 @@ function App() {
const read=()=>{api<BambuCloudState>('/bambu-cloud').then(setBambuCloud).catch(()=>setBambuCloud(null));};
read();window.addEventListener('bambu-cloud-changed',read);return()=>window.removeEventListener('bambu-cloud-changed',read);
},[]);
useEffect(()=>{
if(!bambuCloud?.logged_in)return;
const controller=new AbortController();
const refresh=()=>{void api<BambuCloudState>('/bambu-cloud',{signal:controller.signal}).then(setBambuCloud).catch(()=>{});};
const timer=window.setInterval(refresh,bambuCloudOpen?5000:30000);
return()=>{controller.abort();window.clearInterval(timer);};
},[bambuCloud?.logged_in,bambuCloudOpen]);
const syncedCatalog=useRef<number|null>(null);
useEffect(()=>{
const updated=bambuCloud?.preset_sync?.catalog_changed_at;
if(updated&&updated!==syncedCatalog.current){
syncedCatalog.current=updated;setProfileCatalogToken(value=>value+1);
}
},[bambuCloud?.preset_sync?.catalog_changed_at]);
const [plateSequence,setPlateSequence]=useState(false);
const [plateCompatibility,setPlateCompatibility]=useState(false);
const [plateSettings,setPlateSettings]=useState(false);
@@ -273,6 +290,24 @@ function App() {
const [clipboardToken,setClipboardToken]=useState<string|null>(()=>readClipboardStorage<string>(':current'));
const [clipboardPending,setClipboardPending]=useState<ClipboardPending|null>(()=>readClipboardStorage<ClipboardPending>(':pending'));
const [importRequest,setImportRequest]=useState<ImportRequest|null>(null);
const [externalJob,setExternalJob]=useState<string|null>(()=>new URLSearchParams(window.location.search).get('import-job'));
const [openingExternal,setOpeningExternal]=useState(false);
useEffect(()=>{
if(isDemo)return;
const controller=new AbortController();
const receive=receiveExternalModel(async file=>{
setOpeningExternal(true);
try{
const task=await uploadExternalModel(file,controller.signal);
const url=new URL(window.location.href);
url.hash='';url.searchParams.set('import-job',task.id);
window.history.replaceState(null,'',url);
setExternalJob(task.id);
}finally{if(!controller.signal.aborted)setOpeningExternal(false);}
},reason=>{if(!controller.signal.aborted)setError(reason);});
return()=>{controller.abort();receive?.();};
},[]);
const [shortcutList,setShortcutList]=useState(false),[palette,setPalette]=useState(false);
// A handy model import still waiting for desktop's follow-up actions; null project means a new project.
const handyImport=useRef<{model:HandyModel;projectId:string|null}|null>(null);
@@ -531,7 +566,7 @@ function App() {
const projectId = new URLSearchParams(window.location.search).get('project')??(isDemo?demoManifest.examples[0].id:null);
let disposed = false;
void refresh().then(async values => {
if (disposed || startupHandled.current || projectId) return;
if (disposed || startupHandled.current || projectId || hasExternalModelLaunch()) return;
const printing=values;
setStartupEmpty(printing.length === 0);
// The server compares immutable snapshots with the checkpoint; revision
@@ -2142,7 +2177,8 @@ function App() {
{shortcutList&&<ShortcutList close={()=>setShortcutList(false)}/>}
{palette&&<CommandPalette schema={schema} close={()=>setPalette(false)}
setting={project&&projectConfigured?key=>setSettingFocus(value=>({key,nonce:(value?.nonce??0)+1})):undefined}/>}
<div className="app-notices"> <Imports project={project} schema={schema} libraryChanged={()=>setProfileCatalogToken(value=>value+1)} manage={()=>{openPrinterManagement();}} historyContainer={importHistoryRoot} request={importRequest} consume={()=>setImportRequest(null)} completed={async(task:ImportTask,explicit:boolean)=>{
<div className="app-notices">{openingExternal&&<p role="status">{t('Opening external model…')}</p>}
<Imports externalJob={externalJob} project={project} schema={schema} libraryChanged={()=>setProfileCatalogToken(value=>value+1)} manage={()=>{openPrinterManagement();}} historyContainer={importHistoryRoot} request={importRequest} consume={()=>setImportRequest(null)} completed={async(task:ImportTask,explicit:boolean)=>{
await edits.current;
const current=latest.current;
if(!task.result)return;
@@ -2152,6 +2188,10 @@ function App() {
const value=await api<Project>(`/projects/${task.result.project_id}/open`,jsonRequest('POST',{}));
const oldCount=current?.state.objects.length??0;
acceptProject(value,false,task.project_id===current?.id?'edit':'open');
if(task.id===externalJob){
const url=new URL(window.location.href);url.searchParams.delete('import-job');
window.history.replaceState(null,'',url);setExternalJob(null);
}
if(task.model_edit&&value.revision===task.result.revision)selectTargets(value.state.operation_report?.selection??[],false,false);
else if(task.project_id===current?.id&&value.state.objects.length>oldCount)selectTargets([{object:oldCount,instance:0}],false,false);
setJob(null);setShowPreview(false);setSceneFrame(value=>value+1);await refresh();
@@ -2220,9 +2260,9 @@ function App() {
generate={generateMotionCalibration} reload={reloadMotionCalibration} close={()=>setMotionCalibration(null)}
openProjects={()=>{setMotionCalibration(null);selectWorkspace('project');}}/>}
{aboutOpen&&<AboutDialog close={()=>setAboutOpen(false)}/>}
{bambuCloudOpen&&bambuCloud&&<BambuCloudAccount close={()=>setBambuCloudOpen(false)} state={bambuCloud} changed={setBambuCloud} job={job}/>}
{bambuCloudOpen&&bambuCloud&&<BambuCloudAccount close={()=>setBambuCloudOpen(false)} state={bambuCloud} changed={setBambuCloud} job={job} openPresets={profileBundleTools&&(!localUser||localUser.admin)?()=>{setBambuCloudOpen(false);setProfileBundlesOpen(true);}:undefined} addPrinter={(!localUser||localUser.admin||localUser.can_add_printers)?printer=>{if(openPrinterManagement()){setCloudPrinterRequest(printer);setBambuCloudOpen(false);}}:undefined}/>}
{cloudAccountOpen&&<CloudAccount close={()=>setCloudAccountOpen(false)} schema={schema} changed={()=>setProfileCatalogToken(value=>value+1)}/>}
{profileBundlesOpen&&<ProfileBundles close={()=>setProfileBundlesOpen(false)} changed={()=>setProfileCatalogToken(value=>value+1)} schema={schema} openAccount={()=>{setProfileBundlesOpen(false);setCloudAccountOpen(true);}}/>}
{profileBundlesOpen&&<ProfileBundles bambuCloud={bambuCloud?.logged_in&&(!localUser||localUser.admin)} close={()=>setProfileBundlesOpen(false)} changed={()=>setProfileCatalogToken(value=>value+1)} schema={schema} openAccount={()=>{setProfileBundlesOpen(false);setCloudAccountOpen(true);}}/>}
{slotRemoval&&<RemoveFilamentSlot {...slotRemoval} close={()=>setSlotRemoval(null)} changed={value=>{if(latest.current?.id===value.id){acceptProject(value);setProjectFilamentSlot(0);setHistoryReset(value=>value+1);}void refresh();}}/>}
{presetCopy&&<ProjectPresetSaveAs label={presetCopy.target.preset.label} close={()=>setPresetCopy(null)} save={async(name,id)=>{
const {target,projectId,revision}=presetCopy;
@@ -2250,7 +2290,7 @@ function App() {
{activeWorkspace==='materials'&&!isDemo&&<FilamentProductLibrary key={managerReset} active token={profileCatalogToken}
changed={()=>setProfileCatalogToken(value=>value+1)} onDirty={dirty=>{machineLibraryDirty.current=dirty;}}
editPreset={(machine,profile,preset)=>{if(machineLibraryDirty.current&&!window.confirm(t('Discard unsaved changes?')))return;machineLibraryDirty.current=false;setOwnedOrigin('materials');setOwnedPreset({machine,profile,preset});selectWorkspace('printers');}}/>}
<div hidden={activeWorkspace!=='printers'||!!ownedPreset||!!deviceTarget}><MachineLibrary key={managerReset} active={activeWorkspace==='printers'&&!ownedPreset&&!deviceTarget} openDevice={id=>setDeviceTarget(id)} token={profileCatalogToken}
<div hidden={activeWorkspace!=='printers'||!!ownedPreset||!!deviceTarget}><MachineLibrary bambuCloud={bambuCloud} openBambuAccount={()=>setBambuCloudOpen(true)} cloudRequest={cloudPrinterRequest} consumeCloudRequest={()=>setCloudPrinterRequest(undefined)} key={managerReset} active={activeWorkspace==='printers'&&!ownedPreset&&!deviceTarget} openDevice={id=>setDeviceTarget(id)} token={profileCatalogToken}
changed={()=>setProfileCatalogToken(value=>value+1)} onDirty={dirty=>{machineLibraryDirty.current=dirty;}}
editPreset={(machine,profile,preset)=>{
if(ownedPreset?.machine.id===machine.id&&ownedPreset.profile.id===profile.id&&ownedPreset.preset.id===preset.id){
+6
View File
@@ -139,6 +139,12 @@
.device-material-heading input.device-slot-color-picker{width:44px;min-width:44px;height:40px;padding:4px;cursor:pointer;border:1px solid var(--wb-border);border-radius:6px}
.device-slot-color-picker::-webkit-color-swatch-wrapper{padding:0}
.device-slot-color-picker::-webkit-color-swatch{border:0;border-radius:3px}
.device-slot-color-picker[data-transparent]::-webkit-color-swatch{
background:repeating-conic-gradient(var(--wb-border) 0% 25%,transparent 0% 50%) 0 0 / 8px 8px!important;
}
.device-slot-color-picker[data-transparent]::-moz-color-swatch{
background:repeating-conic-gradient(var(--wb-border) 0% 25%,transparent 0% 50%) 0 0 / 8px 8px!important;
}
.device-diagnostic-message{white-space:pre-wrap;overflow-wrap:anywhere;max-width:100%;padding:12px;border:1px solid var(--wb-border);border-radius:8px}
.device-object-list{display:grid;gap:8px;max-height:18rem;overflow:auto;padding:8px 4px 8px 0}