commit b0de8cf38c38b3ca63a713fc5f43a7e62ca4b325 Author: Dark98 Date: Thu May 14 02:27:26 2026 +0100 Initial Commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9acb106 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +dist/ +bin/ +.env +*.exe +*.log + diff --git a/Dockerfile.dev b/Dockerfile.dev new file mode 100644 index 0000000..afb12dc --- /dev/null +++ b/Dockerfile.dev @@ -0,0 +1,14 @@ +FROM golang:1.22-alpine + +ARG KA_VERSION=dev + +WORKDIR /workspace + +COPY go.mod ./ +COPY go.sum ./ +RUN go mod download + +COPY . . +RUN go build -ldflags "-X main.serverVersion=${KA_VERSION}" -o /usr/local/bin/klipperanywhere-server ./cmd/server +RUN go build -ldflags "-X main.agentVersion=${KA_VERSION}" -o /usr/local/bin/klipperanywhere-agent ./cmd/agent +RUN go build -o /usr/local/bin/klipperanywhere-mock-moonraker ./cmd/mock-moonraker diff --git a/Dockerfile.release b/Dockerfile.release new file mode 100644 index 0000000..f9cd4e4 --- /dev/null +++ b/Dockerfile.release @@ -0,0 +1,21 @@ +FROM golang:1.22-alpine AS build + +ARG KA_VERSION=dev + +WORKDIR /workspace + +COPY go.mod ./ +COPY go.sum ./ +RUN go mod download + +COPY . . +RUN mkdir -p /out \ + && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-X main.serverVersion=${KA_VERSION}" -o /out/klipperanywhere-server-linux-amd64 ./cmd/server \ + && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-X main.agentVersion=${KA_VERSION}" -o /out/klipperanywhere-agent-linux-amd64 ./cmd/agent \ + && CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-X main.agentVersion=${KA_VERSION}" -o /out/klipperanywhere-agent-linux-arm64 ./cmd/agent \ + && CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-X main.agentVersion=${KA_VERSION}" -o /out/klipperanywhere-agent-linux-armv7 ./cmd/agent \ + && CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags "-X main.agentVersion=${KA_VERSION}" -o /out/klipperanywhere-agent-linux-mipsle ./cmd/agent \ + && printf '%s\n' "${KA_VERSION}" > /out/VERSION.txt + +FROM scratch AS release +COPY --from=build /out /out diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..1199d9a --- /dev/null +++ b/Makefile @@ -0,0 +1,23 @@ +APP_NAME := klipperanywhere-agent +DIST_DIR := dist +VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || git rev-parse --short HEAD 2>/dev/null || echo dev) + +.PHONY: build-agent build-server test test-live-printer clean +build-server: + CGO_ENABLED=0 go build -ldflags "-X main.serverVersion=$(VERSION)" -o $(DIST_DIR)/klipperanywhere-server ./cmd/server + +build-agent: + mkdir -p $(DIST_DIR) + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-X main.agentVersion=$(VERSION)" -o $(DIST_DIR)/$(APP_NAME)-linux-amd64 ./cmd/agent + CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-X main.agentVersion=$(VERSION)" -o $(DIST_DIR)/$(APP_NAME)-linux-arm64 ./cmd/agent + CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-X main.agentVersion=$(VERSION)" -o $(DIST_DIR)/$(APP_NAME)-linux-armv7 ./cmd/agent + CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags "-X main.agentVersion=$(VERSION)" -o $(DIST_DIR)/$(APP_NAME)-linux-mipsle ./cmd/agent + +test: + go test ./... + +test-live-printer: + docker run --rm -e KA_RUN_LIVE_SMOKE=1 -e KA_LIVE_SMOKE_URL=http://host.docker.internal:8080 klipperanywhere-server sh -c "cd /workspace && go test ./cmd/server -run TestLiveRealPrinterSmoke -count=1" + +clean: + rm -rf $(DIST_DIR) diff --git a/README.md b/README.md new file mode 100644 index 0000000..4d3a14c --- /dev/null +++ b/README.md @@ -0,0 +1,86 @@ +# KlipperAnywhere + +KlipperAnywhere is an open-source, self-hosted remote access layer for 3D printers. +The first target is Klipper printers running Moonraker, with a design that can later +support OctoPrint, camera streams, notifications, and failure detection. + +## Goals + +- Self-hosted control plane with no mandatory third-party cloud. +- Secure remote access to Moonraker, Mainsail, Fluidd, and webcams. +- Printer-side agent that only opens outbound connections. +- Multi-printer support from a single server. +- Clear permission boundaries for read-only monitoring and active printer control. +- Optional integrations for notifications and AI-based failure detection. + +## Non-Goals For The MVP + +- Replacing Mainsail or Fluidd. +- Building a slicer, print queue manager, or firmware manager. +- Requiring inbound firewall or router port forwarding to the printer network. +- Training a custom failure-detection model before the access layer is stable. + +## MVP Scope + +1. A self-hosted server that users can run with Docker Compose. +2. A printer-side agent that connects to the server over a mutually authenticated tunnel. +3. Reverse proxy access to Moonraker and the printer UI. +4. Webcam snapshot and MJPEG/WebRTC relay support. +5. Basic user auth, printer registration, and access tokens. +6. Audit logging for sensitive actions such as emergency stop, pause, resume, and file upload. + +## Proposed Components + +- `server`: Public HTTPS entry point, user auth, printer registry, tunnel broker, reverse proxy. +- `agent`: Lightweight service installed near the printer, connects to Moonraker and local webcams. +- `web`: Management UI for users, printers, sessions, and connection health. +- `docs`: Architecture, deployment, threat model, and operating guides. + +## Architecture + +See [docs/architecture.md](docs/architecture.md). + +## Local Development + +See [docs/development.md](docs/development.md). + +## Agent Configuration + +See [docs/agent-config.md](docs/agent-config.md). + +## Agent Installation + +See [docs/install-agent.md](docs/install-agent.md). + +## Authentication + +See [docs/auth.md](docs/auth.md). + +## Security Principles + +- The printer network should not need exposed inbound ports. +- The agent should authenticate the server before sending printer traffic. +- Every printer should have scoped credentials that can be revoked independently. +- Remote access should support read-only mode. +- Dangerous actions should be logged and optionally gated behind confirmation. + +## Development Status + +This repository has a local Docker Compose development stack with a Go server, +Go printer-side agent, mock Moonraker service, authenticated dashboard, Moonraker +proxy routes, camera snapshot/stream relay, and a first-pass Mainsail/Fluidd UI +proxy. The current server defaults printer control traffic to read-only mode. + +## Printer Agent Target + +The printer-side agent should be written in Go and distributed as a single binary. +The initial release should target common Klipper hosts and rooted printer appliances: + +- Linux `arm64` +- Linux `armv7` +- Linux `mipsle`, if required by Creality-style embedded boards +- Linux `amd64` + +The installer should support full Linux hosts with `systemd`, OpenRC or SysV init, +plus constrained embedded firmware where only BusyBox-style init scripts or manual +startup hooks are available. diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..fe6054a --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,8 @@ +.gradle/ +build/ +app/build/ +.idea/ +local.properties +captures/ +*.iml +*.log diff --git a/android/README.md b/android/README.md new file mode 100644 index 0000000..e127b82 --- /dev/null +++ b/android/README.md @@ -0,0 +1,42 @@ +# KlipperAnywhere Android + +Native Android client for the current KlipperAnywhere server. + +This app talks directly to the server APIs and renders the main product surfaces +with Compose, so it mirrors the existing web experience without embedding a +browser UI. + +Covered screens: + +- Server setup and login +- Dashboard and printer detail +- Printer settings +- Account password change +- Admin notifications and connected printers +- Users +- Audit log +- SSH installer + +Notes: + +- Set the server URL on first launch. +- Use `http://` for local development or `https://` for production. +- The app stores the server URL locally, but login sessions still depend on the + server cookie lifetime. + +Open `android/` in Android Studio to sync the project. + +From the command line you can install and launch on a Wi-Fi ADB device with: + +```bash +./gradlew wifiAdbRunDebug -PwifiAdbTarget=192.168.1.50:5555 +``` + +If the device is already connected over ADB Wi-Fi, you can point the task at +the same `host:port` serial and it will install plus launch the app. + +On Windows PowerShell, use: + +```powershell +.\gradlew.ps1 wifiAdbRunDebug -PwifiAdbTarget=192.168.1.50:5555 +``` diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..b841d3a --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,214 @@ +import java.io.ByteArrayOutputStream +import java.io.File +import java.util.Properties +import org.gradle.api.GradleException + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +fun Project.readAndroidSdkDir(): File { + val localPropertiesFile = rootProject.file("local.properties") + if (localPropertiesFile.exists()) { + val properties = Properties().apply { + localPropertiesFile.inputStream().use { load(it) } + } + properties.getProperty("sdk.dir")?.let { sdkDir -> + return File(sdkDir) + } + } + + val envSdkDir = providers.environmentVariable("ANDROID_SDK_ROOT").orNull + ?: providers.environmentVariable("ANDROID_HOME").orNull + if (envSdkDir != null) { + return File(envSdkDir) + } + + throw GradleException("Android SDK not found. Set sdk.dir in local.properties or ANDROID_SDK_ROOT.") +} + +fun Project.adbExecutable(): File { + val binary = if (System.getProperty("os.name").contains("Windows", ignoreCase = true)) "adb.exe" else "adb" + return File(readAndroidSdkDir(), "platform-tools/$binary") +} + +data class AdbTarget( + val serial: String, + val shouldConnect: Boolean, +) + +fun Project.resolveWifiAdbTarget(): AdbTarget { + val explicitTarget = providers.gradleProperty("wifiAdbTarget") + .orElse(providers.gradleProperty("wifiAdbSerial")) + .orNull + ?.trim() + ?.takeIf { it.isNotBlank() } + + if (explicitTarget != null) { + return AdbTarget(serial = explicitTarget, shouldConnect = true) + } + + val stdout = ByteArrayOutputStream() + project.exec { + commandLine(adbExecutable().absolutePath, "devices") + standardOutput = stdout + isIgnoreExitValue = true + } + + val devices = stdout + .toString(Charsets.UTF_8.name()) + .lineSequence() + .drop(1) + .mapNotNull { line -> + val trimmed = line.trim() + if (trimmed.isBlank() || trimmed.startsWith("*")) return@mapNotNull null + val serial = trimmed.substringBefore('\t') + val status = trimmed.substringAfter('\t', "").substringBefore(' ') + if (status != "device") return@mapNotNull null + serial + } + .toList() + + if (devices.isEmpty()) { + throw GradleException( + "No adb device is connected. Connect one over Wi-Fi or pass -PwifiAdbTarget=host:port.", + ) + } + + val wifiDevices = devices.filter { ":" in it } + if (wifiDevices.size == 1) { + return AdbTarget(serial = wifiDevices.single(), shouldConnect = false) + } + + if (devices.size == 1) { + return AdbTarget(serial = devices.single(), shouldConnect = false) + } + + throw GradleException( + buildString { + appendLine("Multiple adb devices are connected:") + devices.forEach { appendLine(" - $it") } + append("Pass -PwifiAdbTarget=host:port or -PwifiAdbSerial=serial to choose one.") + }, + ) +} + +android { + namespace = "com.klipperanywhere.android" + compileSdk = 34 + + defaultConfig { + applicationId = "com.klipperanywhere.android" + minSdk = 26 + targetSdk = 34 + versionCode = 1 + versionName = "0.1.0" + } + + buildFeatures { + compose = true + } + + composeOptions { + kotlinCompilerExtensionVersion = "1.5.14" + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = "17" + } + + packaging { + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } +} + +dependencies { + implementation(platform("androidx.compose:compose-bom:2024.06.00")) + implementation("androidx.activity:activity-compose:1.9.0") + implementation("androidx.compose.foundation:foundation") + implementation("androidx.compose.material:material") + implementation("androidx.compose.material3:material3") + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.ui:ui-text") + implementation("androidx.compose.ui:ui-tooling-preview") + implementation("androidx.core:core-ktx:1.13.1") + implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.1.0") + implementation("androidx.security:security-crypto:1.1.0-alpha06") + implementation("com.google.android.material:material:1.12.0") + implementation("com.squareup.okhttp3:okhttp:4.12.0") + implementation("com.squareup.okhttp3:okhttp-urlconnection:4.12.0") + implementation("com.squareup.okhttp3:logging-interceptor:4.12.0") + implementation("io.coil-kt:coil-compose:2.6.0") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1") + debugImplementation("androidx.compose.ui:ui-tooling") +} + +val adbFile = adbExecutable() +val debugApk = layout.buildDirectory.file("outputs/apk/debug/app-debug.apk") +val launchActivity = "com.klipperanywhere.android/.MainActivity" + +tasks.register("wifiAdbInstallDebug") { + group = "install" + description = "Installs the debug APK to a Wi-Fi ADB device." + dependsOn("assembleDebug") + + doLast { + val target = resolveWifiAdbTarget() + + if (target.shouldConnect) { + project.exec { + commandLine(adbFile.absolutePath, "connect", target.serial) + } + } + + project.exec { + commandLine(adbFile.absolutePath, "-s", target.serial, "install", "-r", debugApk.get().asFile.absolutePath) + } + } +} + +tasks.register("wifiAdbRunDebug") { + group = "run" + description = "Installs the debug APK to a Wi-Fi ADB device and launches the app." + dependsOn("wifiAdbInstallDebug") + + doLast { + val target = resolveWifiAdbTarget() + + project.exec { + commandLine( + adbFile.absolutePath, + "-s", + target.serial, + "shell", + "am", + "start", + "-n", + launchActivity, + "-a", + "android.intent.action.MAIN", + "-c", + "android.intent.category.LAUNCHER", + ) + } + } +} + +tasks.register("killAdbServer") { + group = "adb" + description = "Stops the local adb server." + + doLast { + project.exec { + commandLine(adbFile.absolutePath, "kill-server") + } + } +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..0af6c4f --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/com/klipperanywhere/android/ApiClient.kt b/android/app/src/main/java/com/klipperanywhere/android/ApiClient.kt new file mode 100644 index 0000000..3b5d5ed --- /dev/null +++ b/android/app/src/main/java/com/klipperanywhere/android/ApiClient.kt @@ -0,0 +1,648 @@ +package com.klipperanywhere.android + +import android.content.Context +import coil.ImageLoader +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.FormBody +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.JavaNetCookieJar +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONArray +import org.json.JSONObject +import java.net.CookieManager +import java.net.CookiePolicy +import java.net.HttpCookie + +class ApiClient { + private val cookieManager = CookieManager().apply { + setCookiePolicy(CookiePolicy.ACCEPT_ALL) + } + private val client = OkHttpClient.Builder() + .cookieJar(JavaNetCookieJar(cookieManager)) + .followRedirects(true) + .followSslRedirects(true) + .build() + + private var baseUrl = "http://127.0.0.1:8080".toHttpUrl() + + fun setBaseUrl(rawUrl: String) { + baseUrl = normalizeServerUrl(rawUrl)?.toHttpUrl() ?: baseUrl + } + + fun imageLoader(context: Context): ImageLoader { + return ImageLoader.Builder(context) + .okHttpClient(client) + .build() + } + + suspend fun loadSession(): SessionInfo? = withContext(Dispatchers.IO) { + val response = request(Request.Builder().url(url("/api/session")).get().build()) + response.use { resp -> + if (!resp.isSuccessful) { + return@withContext null + } + val payload = JSONObject(resp.body?.string().orEmpty()) + if (!payload.optBoolean("authenticated", false)) { + return@withContext null + } + payload.toSessionInfo() + } + } + + suspend fun login(username: String, password: String): SessionInfo? = withContext(Dispatchers.IO) { + val body = FormBody.Builder() + .add("username", username) + .add("password", password) + .build() + val response = request( + Request.Builder() + .url(url("/login")) + .post(body) + .build(), + ) + response.close() + loadSession() + } + + suspend fun logout(csrfToken: String): Boolean = withContext(Dispatchers.IO) { + val body = FormBody.Builder() + .add("csrf_token", csrfToken) + .build() + val response = request( + Request.Builder() + .url(url("/logout")) + .post(body) + .build(), + ) + response.close() + true + } + + suspend fun listPrinters(): List = withContext(Dispatchers.IO) { + val payload = getJson("/api/printers") ?: return@withContext emptyList() + payload.optJSONArray("printers").toObjectList().map { it.toPrinterSummary() } + } + + suspend fun getPrinter(printerId: String): PrinterDetail? = withContext(Dispatchers.IO) { + val payload = getJson("/api/printers/${printerId.encodePathSegment()}") ?: return@withContext null + payload.toPrinterDetail(printerId) + } + + suspend fun updatePrinterSettings(printerId: String, body: JSONObject): PrinterDetail? = withContext(Dispatchers.IO) { + val payload = patchJson("/api/printers/${printerId.encodePathSegment()}/settings", body) ?: return@withContext null + payload.toPrinterDetailResponse(printerId) + } + + suspend fun getPrinterSettings(printerId: String): Pair = withContext(Dispatchers.IO) { + val payload = getJson("/api/printers/${printerId.encodePathSegment()}/settings") ?: return@withContext null to null + val settings = payload.optJSONObject("settings")?.toPrinterSettingsView() + val health = getPrinter(printerId)?.health + settings to health + } + + suspend fun updateAccount(currentPassword: String, newPassword: String, csrfToken: String): Boolean = withContext(Dispatchers.IO) { + val body = JSONObject() + .put("current_password", currentPassword) + .put("new_password", newPassword) + val response = patchJson("/api/account", body, csrfToken) + response != null + } + + suspend fun listUsers(): List = withContext(Dispatchers.IO) { + val payload = getJson("/api/users") ?: return@withContext emptyList() + payload.optJSONArray("users").toObjectList().map { it.toUserRecord() } + } + + suspend fun createUser(body: JSONObject, csrfToken: String): Boolean = withContext(Dispatchers.IO) { + postJson("/api/users", body, csrfToken) != null + } + + suspend fun updateUser(userId: String, body: JSONObject, csrfToken: String): Boolean = withContext(Dispatchers.IO) { + patchJson("/api/users/${userId.encodePathSegment()}", body, csrfToken) != null + } + + suspend fun deleteUser(userId: String, csrfToken: String): Boolean = withContext(Dispatchers.IO) { + delete("/api/users/${userId.encodePathSegment()}", csrfToken) + } + + suspend fun getNotifications(): AdminNotificationSettings? = withContext(Dispatchers.IO) { + val payload = getJson("/api/notifications") ?: return@withContext null + val record = payload.optJSONObject("notifications") ?: return@withContext null + record.toAdminNotificationSettings() + } + + suspend fun updateNotifications(body: JSONObject, csrfToken: String): AdminNotificationSettings? = withContext(Dispatchers.IO) { + val payload = patchJson("/api/notifications", body, csrfToken) ?: return@withContext null + payload.optJSONObject("notifications")?.toAdminNotificationSettings() + } + + suspend fun testNotifications(body: JSONObject, csrfToken: String): String? = withContext(Dispatchers.IO) { + val response = postJson("/api/notifications/test", body, csrfToken) ?: return@withContext null + response.optString("message").takeIf { it.isNotBlank() } + } + + suspend fun getAudit(limit: Int = 100): List = withContext(Dispatchers.IO) { + val payload = getJson("/api/audit?limit=$limit") ?: return@withContext emptyList() + payload.optJSONArray("events").toObjectList().map { it.toAuditEvent() } + } + + suspend fun startInstall(body: JSONObject, csrfToken: String): JSONObject? = withContext(Dispatchers.IO) { + postJson("/api/install/ssh", body, csrfToken) + } + + suspend fun pollInstallJob(jobId: String): InstallJob? = withContext(Dispatchers.IO) { + val payload = getJson("/api/install/ssh/jobs/${jobId.encodePathSegment()}") ?: return@withContext null + payload.toInstallJob() + } + + suspend fun triggerAgentUpdate(printerId: String, csrfToken: String): JSONObject? = withContext(Dispatchers.IO) { + postJson("/api/printers/${printerId.encodePathSegment()}/agent/update", JSONObject(), csrfToken) + } + + suspend fun getAccountSession(): SessionInfo? = loadSession() + + fun requestPrinterSnapshotUrl(printerId: String, cameraName: String): String { + return url("/p/${printerId.encodePathSegment()}/camera/${cameraName.encodePathSegment()}/snapshot") + } + + fun requestPrinterStreamUrl(printerId: String, cameraName: String): String { + return url("/p/${printerId.encodePathSegment()}/camera/${cameraName.encodePathSegment()}/stream") + } + + fun printerUiUrl(printerId: String): String { + return url("/printers/${printerId.encodePathSegment()}/ui/") + } + + fun printerInfoUrl(printerId: String): String { + return url("/p/${printerId.encodePathSegment()}/moonraker/printer/info") + } + + fun printerHealthUrl(printerId: String): String { + return url("/api/printers/${printerId.encodePathSegment()}/health") + } + + fun baseUrlString(): String = baseUrl.toString().trimEnd('/') + + fun okHttpClient(): OkHttpClient = client + + fun webViewCookies(): List = cookieManager.cookieStore.cookies.toList() + + private fun url(path: String): String { + return baseUrl.newBuilder() + .encodedPath(path.substringBefore('?').takeIf { it.startsWith('/') } ?: "/") + .apply { + val query = path.substringAfter('?', "") + if (query.isNotBlank()) { + encodedQuery(query) + } + } + .build() + .toString() + } + + suspend fun getText(path: String): Pair = withContext(Dispatchers.IO) { + val response = request(Request.Builder().url(url(path)).get().build()) + response.use { resp -> + resp.code to (resp.body?.string().orEmpty()) + } + } + + suspend fun postText(path: String, body: String, csrfToken: String? = null): Pair = withContext(Dispatchers.IO) { + val response = request( + Request.Builder() + .url(url(path)) + .addCsrf(csrfToken) + .post(body.toRequestBody(TEXT_MEDIA)) + .build(), + ) + response.use { resp -> + resp.code to (resp.body?.string().orEmpty()) + } + } + + suspend fun patchText(path: String, body: String, csrfToken: String? = null): Pair = withContext(Dispatchers.IO) { + val response = request( + Request.Builder() + .url(url(path)) + .addCsrf(csrfToken) + .patch(body.toRequestBody(TEXT_MEDIA)) + .build(), + ) + response.use { resp -> + resp.code to (resp.body?.string().orEmpty()) + } + } + + private fun request(request: Request) = client.newCall(request).execute() + + private fun getJson(path: String): JSONObject? { + val response = request(Request.Builder().url(url(path)).get().build()) + response.use { resp -> + if (!resp.isSuccessful) { + return null + } + return JSONObject(resp.body?.string().orEmpty()) + } + } + + private fun postJson(path: String, body: JSONObject, csrfToken: String? = null): JSONObject? { + val response = request( + Request.Builder() + .url(url(path)) + .addCsrf(csrfToken) + .post(body.toString().toRequestBody(JSON_MEDIA)) + .build(), + ) + response.use { resp -> + if (!resp.isSuccessful) { + return null + } + return JSONObject(resp.body?.string().orEmpty().ifBlank { "{}" }) + } + } + + private fun patchJson(path: String, body: JSONObject, csrfToken: String? = null): JSONObject? { + val response = request( + Request.Builder() + .url(url(path)) + .addCsrf(csrfToken) + .patch(body.toString().toRequestBody(JSON_MEDIA)) + .build(), + ) + response.use { resp -> + if (!resp.isSuccessful) { + return null + } + return JSONObject(resp.body?.string().orEmpty().ifBlank { "{}" }) + } + } + + private fun delete(path: String, csrfToken: String): Boolean { + val response = request( + Request.Builder() + .url(url(path)) + .addCsrf(csrfToken) + .delete() + .build(), + ) + response.close() + return true + } + + private fun Request.Builder.addCsrf(csrfToken: String?): Request.Builder { + if (!csrfToken.isNullOrBlank()) { + header("X-CSRF-Token", csrfToken) + } + return this + } + + companion object { + private val JSON_MEDIA = "application/json; charset=utf-8".toMediaType() + private val TEXT_MEDIA = "text/plain; charset=utf-8".toMediaType() + } +} + +private fun JSONArray?.toObjectList(): List = buildList { + if (this@toObjectList == null) { + return@buildList + } + for (index in 0 until length()) { + optJSONObject(index)?.let { add(it) } + } +} + +private fun JSONObject.toSessionInfo(): SessionInfo { + return SessionInfo( + authenticated = optBoolean("authenticated", false), + userId = optString("user_id"), + username = optString("username"), + role = optString("role"), + isAdmin = optBoolean("is_admin", false), + printerGrants = optJSONArray("printer_grants").toObjectList().map { it.toPrinterGrant() }, + csrfToken = optString("csrf_token"), + serverVersion = optString("server_version"), + ) +} + +private fun JSONObject.toPrinterGrant(): PrinterGrant { + return PrinterGrant( + printerId = optString("printer_id"), + access = optString("access"), + ) +} + +private fun JSONObject.toCameraInfo(): CameraInfo { + return CameraInfo( + name = optString("name"), + hasSnapshot = optBoolean("has_snapshot", false), + hasStream = optBoolean("has_stream", false), + aspectRatio = optStringOrNull("aspect_ratio"), + rotation = if (has("rotation")) optInt("rotation") else null, + flipHorizontal = optBoolean("flip_horizontal", false), + flipVertical = optBoolean("flip_vertical", false), + location = optStringOrNull("location"), + service = optStringOrNull("service"), + source = optStringOrNull("source"), + ) +} + +private fun JSONObject.toPrinterHealth(): PrinterHealth { + return PrinterHealth( + connected = true, + moonrakerReachable = optBoolean("moonraker_reachable", false), + moonrakerState = optStringOrNull("moonraker_state"), + moonrakerMessage = optStringOrNull("moonraker_message"), + checkedAtUnix = if (has("checked_at_unix")) optLong("checked_at_unix") else null, + uiReachable = optBoolean("ui_reachable", false), + uiSource = optStringOrNull("ui_source"), + uiUrl = optStringOrNull("ui_url"), + uiAutoDetect = optBoolean("ui_auto_detect", false), + controlMode = optStringOrNull("control_mode"), + agentVersion = optStringOrNull("agent_version"), + hostname = optStringOrNull("hostname"), + cameras = optJSONArray("cameras").toObjectList().map { it.toCameraInfo() }, + printStatus = optJSONObject("print_status")?.toPrintStatus(), + ) +} + +private fun JSONObject.toPrinterInfo(): PrinterInfo { + return PrinterInfo( + hostname = optStringOrNull("hostname"), + softwareVersion = optStringOrNull("software_version"), + cpuInfo = optStringOrNull("cpu_info"), + configFile = optStringOrNull("config_file"), + logFile = optStringOrNull("log_file"), + ) +} + +private fun JSONObject.toPrintStatus(): PrintStatus { + val printStats = optJSONObject("print_stats") ?: this + val displayStatus = optJSONObject("display_status") ?: this + return PrintStatus( + state = printStats.optStringOrNull("state"), + filename = printStats.optStringOrNull("filename"), + progress = displayStatus.optDoubleOrNull("progress"), + printDuration = printStats.optDoubleOrNull("print_duration"), + totalDuration = printStats.optDoubleOrNull("total_duration"), + estimatedRemaining = printStats.optDoubleOrNull("estimated_time_remaining") + ?: printStats.optDoubleOrNull("estimated_duration"), + filamentUsed = printStats.optDoubleOrNull("filament_used"), + message = printStats.optStringOrNull("message") ?: displayStatus.optStringOrNull("message"), + moonrakerStatus = optJSONObject("moonraker_status")?.toValueMap(), + moonrakerMetadata = optJSONObject("moonraker_metadata")?.toValueMap(), + moonrakerMetadataFilename = optStringOrNull("moonraker_metadata_filename"), + layerSource = optStringOrNull("layer_source"), + ) +} + +private fun JSONObject.toRecentJob(): RecentJob { + return RecentJob( + filename = optString("filename"), + status = optString("status"), + totalDuration = optDoubleOrNull("total_duration"), + printDuration = optDoubleOrNull("print_duration"), + startTime = if (has("start_time")) optLong("start_time") else null, + endTime = if (has("end_time")) optLong("end_time") else null, + message = optStringOrNull("message"), + ) +} + +private fun JSONObject.toInstallSummary(): InstallSummary { + return InstallSummary( + hostType = optStringOrNull("host_type"), + serverUrl = optStringOrNull("server_url"), + host = optStringOrNull("host"), + port = if (has("port")) optInt("port") else null, + username = optStringOrNull("username"), + moonrakerUrl = optStringOrNull("moonraker_url"), + uiUrl = optStringOrNull("ui_url"), + uiAutoDetect = if (has("ui_auto_detect")) optBoolean("ui_auto_detect") else null, + status = optStringOrNull("status"), + message = optStringOrNull("message"), + error = optStringOrNull("error"), + binarySource = optStringOrNull("binary_source"), + configPath = optStringOrNull("config_path"), + postInstallConnected = if (has("post_install_connected")) optBoolean("post_install_connected") else null, + postInstallMessage = optStringOrNull("post_install_message"), + rollbackPerformed = if (has("rollback_performed")) optBoolean("rollback_performed") else null, + rollbackMessage = optStringOrNull("rollback_message"), + ) +} + +private fun JSONObject.toPrinterSettingsView(): PrinterSettingsView { + return PrinterSettingsView( + displayName = optStringOrNull("display_name"), + controlMode = optStringOrNull("control_mode"), + uiUrl = optStringOrNull("ui_url"), + uiAutoDetect = optBoolean("ui_auto_detect", false), + notificationSnapshotCamera = optStringOrNull("notification_snapshot_camera"), + updatedAt = optStringOrNull("updated_at"), + lastSyncedAt = optStringOrNull("last_synced_at"), + install = optJSONObject("install")?.toInstallSummary(), + printNotificationsEnabled = optBoolean("print_notifications_enabled", false), + notifyPrintStarted = optBoolean("notify_print_started", false), + notifyPrintPaused = optBoolean("notify_print_paused", false), + notifyPrintResumed = optBoolean("notify_print_resumed", false), + notifyPrintCompleted = optBoolean("notify_print_completed", false), + notifyPrintCanceled = optBoolean("notify_print_canceled", false), + notifyPrintFailed = optBoolean("notify_print_failed", false), + notifyFirstLayer = optBoolean("notify_print_first_layer", false), + notifyThirdLayer = optBoolean("notify_print_third_layer", false), + ) +} + +private fun JSONObject.toPrinterSummary(): PrinterSummary { + return PrinterSummary( + printerId = optString("printer_id"), + connected = optBoolean("connected", false), + health = optJSONObject("health")?.toPrinterHealth(), + settings = optJSONObject("settings")?.toPrinterSettingsView() ?: PrinterSettingsView( + displayName = null, + controlMode = null, + uiUrl = null, + uiAutoDetect = false, + notificationSnapshotCamera = null, + updatedAt = null, + lastSyncedAt = null, + install = null, + printNotificationsEnabled = false, + notifyPrintStarted = false, + notifyPrintPaused = false, + notifyPrintResumed = false, + notifyPrintCompleted = false, + notifyPrintCanceled = false, + notifyPrintFailed = false, + notifyFirstLayer = false, + notifyThirdLayer = false, + ), + ) +} + +private fun JSONObject.toPrinterDetailResponse(printerId: String): PrinterDetail { + return PrinterDetail( + printerId = printerId, + connected = optBoolean("connected", false), + health = optJSONObject("health")?.toPrinterHealth(), + info = optJSONObject("info")?.toPrinterInfo(), + printStatus = optJSONObject("print_status")?.toPrintStatus(), + recentJobs = optJSONArray("recent_jobs").toObjectList().map { it.toRecentJob() }, + controlMode = optStringOrNull("control_mode"), + access = optStringOrNull("access"), + settings = optJSONObject("settings")?.toPrinterSettingsView() ?: emptyPrinterSettings(), + settingsSynced = optBoolean("settings_synced", false), + settingsSyncState = optStringOrNull("settings_sync_state"), + settingsSyncDetail = optStringOrNull("settings_sync_detail"), + ) +} + +private fun JSONObject.toPrinterDetail(printerId: String): PrinterDetail { + return toPrinterDetailResponse(printerId) +} + +private fun JSONObject.toUserRecord(): UserRecord { + return UserRecord( + id = optString("id"), + username = optString("username"), + role = optString("role"), + createdAt = optStringOrNull("created_at"), + printerGrants = optJSONArray("printer_grants").toObjectList().map { it.toPrinterGrant() }, + ) +} + +private fun JSONObject.toAdminNotificationSettings(): AdminNotificationSettings { + return AdminNotificationSettings( + telegramEnabled = optBoolean("telegram_enabled", false), + telegramCommandsEnabled = optBoolean("telegram_commands_enabled", false), + telegramBotTokenSet = optBoolean("telegram_bot_token_set", false) || optStringOrNull("telegram_bot_token") != null, + telegramBotToken = optStringOrNull("telegram_bot_token"), + telegramChatId = optStringOrNull("telegram_chat_id"), + ) +} + +private fun JSONObject.toAuditEvent(): AuditEvent { + return AuditEvent( + timestamp = optStringOrNull("timestamp"), + actor = optStringOrNull("actor"), + action = optStringOrNull("action"), + printerId = optStringOrNull("printer_id"), + targetId = optStringOrNull("target_id"), + method = optStringOrNull("method"), + path = optStringOrNull("path"), + detail = optStringOrNull("detail"), + status = if (has("status")) opt("status") else null, + ) +} + +private fun JSONObject.toInstallJob(): InstallJob { + return InstallJob( + id = optString("id"), + status = optStringOrNull("status"), + stage = optStringOrNull("stage"), + message = optStringOrNull("message"), + output = optStringOrNull("output"), + printerId = optStringOrNull("printer_id"), + host = optStringOrNull("host"), + port = if (has("port")) optInt("port") else null, + hostType = optStringOrNull("host_type"), + serverUrl = optStringOrNull("server_url"), + remoteHost = optStringOrNull("remote_host"), + binarySource = optStringOrNull("binary_source"), + configPath = optStringOrNull("config_path"), + postInstallConnected = if (has("post_install_connected")) optBoolean("post_install_connected") else null, + postInstallMessage = optStringOrNull("post_install_message"), + rollbackPerformed = if (has("rollback_performed")) optBoolean("rollback_performed") else null, + rollbackMessage = optStringOrNull("rollback_message"), + ) +} + +private fun emptyPrinterSettings(): PrinterSettingsView = PrinterSettingsView( + displayName = null, + controlMode = null, + uiUrl = null, + uiAutoDetect = false, + notificationSnapshotCamera = null, + updatedAt = null, + lastSyncedAt = null, + install = null, + printNotificationsEnabled = false, + notifyPrintStarted = false, + notifyPrintPaused = false, + notifyPrintResumed = false, + notifyPrintCompleted = false, + notifyPrintCanceled = false, + notifyPrintFailed = false, + notifyFirstLayer = false, + notifyThirdLayer = false, +) + +private fun JSONObject.optStringOrNull(name: String): String? { + if (!has(name) || isNull(name)) { + return null + } + return optString(name).takeIf { it.isNotBlank() } +} + +private fun JSONObject.optDoubleOrNull(name: String): Double? { + if (!has(name) || isNull(name)) { + return null + } + val value = optDouble(name) + return if (value.isNaN()) null else value +} + +private fun JSONObject.toValueMap(): Map { + val map = linkedMapOf() + keys().forEach { key -> + map[key] = toKotlinValue(opt(key)) + } + return map +} + +private fun JSONArray.toValueList(): List { + return buildList { + for (index in 0 until length()) { + add(toKotlinValue(opt(index))) + } + } +} + +private fun toKotlinValue(value: Any?): Any? { + return when (value) { + null, JSONObject.NULL -> null + is JSONObject -> value.toValueMap() + is JSONArray -> value.toValueList() + else -> value + } +} + +internal fun String.encodePathSegment(): String { + return java.net.URLEncoder.encode(this, Charsets.UTF_8.name()).replace("+", "%20") +} + +fun normalizeServerUrl(rawValue: String): String? { + val trimmed = rawValue.trim() + if (trimmed.isBlank()) { + return null + } + val candidate = when { + trimmed.startsWith("http://", ignoreCase = true) || trimmed.startsWith("https://", ignoreCase = true) -> trimmed + else -> "https://$trimmed" + } + return try { + val uri = android.net.Uri.parse(candidate) + val scheme = uri.scheme?.lowercase() + if (scheme != "http" && scheme != "https") { + null + } else if (uri.host.isNullOrBlank()) { + null + } else { + uri.buildUpon().fragment(null).build().toString().trimEnd('/') + } + } catch (_: Throwable) { + null + } +} diff --git a/android/app/src/main/java/com/klipperanywhere/android/CredentialStore.kt b/android/app/src/main/java/com/klipperanywhere/android/CredentialStore.kt new file mode 100644 index 0000000..562dfbb --- /dev/null +++ b/android/app/src/main/java/com/klipperanywhere/android/CredentialStore.kt @@ -0,0 +1,57 @@ +package com.klipperanywhere.android + +import android.content.Context +import androidx.security.crypto.EncryptedSharedPreferences +import androidx.security.crypto.MasterKey + +data class StoredCredentials( + val username: String, + val password: String, +) + +class CredentialStore(context: Context) { + private val prefs = EncryptedSharedPreferences.create( + context, + PREFS_FILE, + MasterKey.Builder(context) + .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) + .build(), + EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, + EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM, + ) + + fun load(serverUrl: String): StoredCredentials? { + val key = keyPrefix(serverUrl) + val username = prefs.getString("${key}username", null)?.trim().orEmpty() + val password = prefs.getString("${key}password", null).orEmpty() + return if (username.isBlank() || password.isBlank()) { + null + } else { + StoredCredentials(username = username, password = password) + } + } + + fun save(serverUrl: String, username: String, password: String) { + val key = keyPrefix(serverUrl) + prefs.edit() + .putString("${key}username", username.trim()) + .putString("${key}password", password) + .apply() + } + + fun clear(serverUrl: String) { + val key = keyPrefix(serverUrl) + prefs.edit() + .remove("${key}username") + .remove("${key}password") + .apply() + } + + private fun keyPrefix(serverUrl: String): String { + return "server:${serverUrl.trim().lowercase()}:" + } + + private companion object { + const val PREFS_FILE = "klipperanywhere_credentials" + } +} diff --git a/android/app/src/main/java/com/klipperanywhere/android/MainActivity.kt b/android/app/src/main/java/com/klipperanywhere/android/MainActivity.kt new file mode 100644 index 0000000..3ab966d --- /dev/null +++ b/android/app/src/main/java/com/klipperanywhere/android/MainActivity.kt @@ -0,0 +1,2879 @@ +@file:OptIn( + androidx.compose.material3.ExperimentalMaterial3Api::class, + androidx.compose.material.ExperimentalMaterialApi::class, +) + +package com.klipperanywhere.android + +import android.content.Context +import android.content.ActivityNotFoundException +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.app.Activity +import android.widget.Toast +import android.webkit.CookieManager as WebCookieManager +import android.webkit.WebChromeClient +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebSettings +import android.webkit.WebView +import android.webkit.WebViewClient +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CenterAlignedTopAppBar +import androidx.compose.material3.Divider +import androidx.compose.material3.FilterChip +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SelectableChipColors +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material.pullrefresh.PullRefreshIndicator +import androidx.compose.material.pullrefresh.pullRefresh +import androidx.compose.material.pullrefresh.rememberPullRefreshState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.viewinterop.AndroidView +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import coil.compose.AsyncImage +import kotlinx.coroutines.launch +import kotlinx.coroutines.delay +import org.json.JSONObject +import java.util.Locale + +private const val PREFS_NAME = "klipperanywhere_android" +private const val PREF_SERVER_URL = "server_url" +private const val PREF_PRINTER_UI_MODE_PREFIX = "printer_ui_mode" + +private enum class PrinterUiLaunchMode { + Embedded, + External, +} + +private enum class Screen { + Setup, + Login, + Dashboard, + PrinterDetail, + PrinterAgent, + PrinterWebUi, + PrinterSettings, + Account, + Admin, + Users, + Audit, + Install, +} + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContent { + KlipperAnywhereTheme { + Surface(color = MaterialTheme.colorScheme.background) { + KlipperAnywhereApp() + } + } + } + } +} + +@Composable +private fun KlipperAnywhereApp() { + val context = LocalContext.current + val api = remember { ApiClient() } + val credentialStore = remember { CredentialStore(context) } + val scope = rememberCoroutineScope() + var serverUrl by rememberSaveable { mutableStateOf(loadSavedServerUrl(context)) } + var session by remember { mutableStateOf(null) } + var screen by rememberSaveable { mutableStateOf(if (serverUrl.isBlank()) Screen.Setup else Screen.Login) } + var printerId by rememberSaveable { mutableStateOf("") } + var appMessage by rememberSaveable { mutableStateOf(null) } + var booting by rememberSaveable { mutableStateOf(serverUrl.isNotBlank()) } + var webUiUrl by rememberSaveable { mutableStateOf("") } + var webUiPrinterLabel by rememberSaveable { mutableStateOf("") } + var webUiReturnScreen by rememberSaveable { mutableStateOf(Screen.Dashboard) } + val savedCredentials = remember(serverUrl) { credentialStore.load(serverUrl) } + var lastBackPressAt by rememberSaveable { mutableStateOf(0L) } + fun appBack() { + screen = when (screen) { + Screen.PrinterAgent -> Screen.PrinterDetail + Screen.PrinterSettings -> Screen.PrinterDetail + Screen.Users, Screen.Audit, Screen.Install -> Screen.Admin + Screen.PrinterDetail -> Screen.Dashboard + Screen.PrinterWebUi -> webUiReturnScreen + Screen.Admin, Screen.Account -> Screen.Dashboard + Screen.Login -> Screen.Setup + Screen.Setup, Screen.Dashboard -> screen + } + } + + BackHandler(enabled = session != null && !booting) { + if (screen == Screen.Dashboard) { + val now = System.currentTimeMillis() + if (now - lastBackPressAt < 2000L) { + (context as? Activity)?.finish() + } else { + lastBackPressAt = now + Toast.makeText(context, "Press back again to exit", Toast.LENGTH_SHORT).show() + } + } else { + appBack() + } + } + + LaunchedEffect(serverUrl) { + if (serverUrl.isBlank()) { + session = null + booting = false + screen = Screen.Setup + return@LaunchedEffect + } + booting = true + try { + api.setBaseUrl(serverUrl) + var connected = false + repeat(3) { attempt -> + try { + session = api.loadSession() + if (session == null) { + if (savedCredentials != null) { + val autoLogin = api.login(savedCredentials.username, savedCredentials.password) + if (autoLogin != null) { + session = autoLogin + screen = Screen.Dashboard + } else { + credentialStore.clear(serverUrl) + appMessage = "Saved credentials no longer work. Please sign in again." + screen = Screen.Login + } + } else { + screen = Screen.Login + } + } else { + screen = Screen.Dashboard + } + connected = true + return@repeat + } catch (_: Throwable) { + if (attempt < 2) { + delay(750) + } + } + } + if (!connected) { + session = null + appMessage = "Unable to connect to the server." + screen = Screen.Setup + } + } catch (_: Throwable) { + session = null + appMessage = "Unable to connect to the server." + screen = Screen.Setup + } finally { + booting = false + } + } + + when { + screen == Screen.Setup -> SetupScreen( + currentServerUrl = serverUrl, + onOpen = { normalized -> + saveServerUrl(context, normalized) + serverUrl = normalized + appMessage = null + screen = Screen.Login + }, + message = appMessage, + ) + + booting -> LoadingScreen(serverUrl) + + session == null -> LoginScreen( + serverUrl = serverUrl, + initialUsername = savedCredentials?.username.orEmpty(), + initialRemember = savedCredentials != null, + errorMessage = appMessage, + onUseDifferentServer = { + session = null + screen = Screen.Setup + }, + onForgetSavedAccount = { + credentialStore.clear(serverUrl) + appMessage = "Saved account cleared." + }, + onLogin = { username, password, rememberCredentials -> + api.setBaseUrl(serverUrl) + val loggedIn = api.login(username, password) + if (loggedIn != null) { + if (rememberCredentials) { + credentialStore.save(serverUrl, username, password) + } else { + credentialStore.clear(serverUrl) + } + session = loggedIn + appMessage = null + screen = Screen.Dashboard + true + } else { + appMessage = "Login failed." + false + } + }, + ) + + else -> AuthenticatedShell( + api = api, + session = session!!, + serverUrl = serverUrl, + screen = screen, + printerId = printerId, + webUiUrl = webUiUrl, + webUiPrinterLabel = webUiPrinterLabel, + onBack = { appBack() }, + onScreenChange = { next -> + screen = next + }, + onPrinterChange = { next -> + printerId = next + }, + onOpenPrinterUi = { targetPrinterId, label, url, returnScreen -> + if (resolvePrinterUiLaunchMode(context, serverUrl, targetPrinterId) == PrinterUiLaunchMode.Embedded) { + webUiUrl = url + webUiPrinterLabel = label + webUiReturnScreen = returnScreen + screen = Screen.PrinterWebUi + } else { + openExternal(context, url) + } + }, + onLogout = { + scope.launch { + val loggedOut = api.logout(session!!.csrfToken) + if (loggedOut) { + credentialStore.clear(serverUrl) + session = null + appMessage = null + webUiUrl = "" + webUiPrinterLabel = "" + webUiReturnScreen = Screen.Dashboard + screen = Screen.Login + } + } + }, + onChangeServer = { + session = null + printerId = "" + webUiUrl = "" + webUiPrinterLabel = "" + webUiReturnScreen = Screen.Dashboard + screen = Screen.Setup + }, + ) + } +} + +@Composable +private fun LoadingScreen(serverUrl: String) { + val background = Brush.verticalGradient( + colors = listOf(Color(0xFF07131F), Color(0xFF102A3D), Color(0xFF1A2430)), + ) + Box( + modifier = Modifier + .fillMaxSize() + .background(background) + .padding(24.dp), + contentAlignment = Alignment.Center, + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text( + text = "Connecting to $serverUrl", + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onBackground, + fontWeight = FontWeight.SemiBold, + ) + Spacer(modifier = Modifier.height(16.dp)) + LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + } + } +} + +@Composable +private fun SetupScreen( + currentServerUrl: String, + onOpen: (String) -> Unit, + message: String?, +) { + val scroll = rememberScrollState() + val background = Brush.verticalGradient( + colors = listOf(Color(0xFF07131F), Color(0xFF102A3D), Color(0xFF1A2430)), + ) + var draftUrl by rememberSaveable(currentServerUrl) { mutableStateOf(currentServerUrl) } + + Box( + modifier = Modifier + .fillMaxSize() + .background(background) + .navigationBarsPadding() + .verticalScroll(scroll) + .padding(20.dp), + ) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.95f)), + elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), + ) { + Column(modifier = Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { + Text( + text = "KlipperAnywhere", + style = MaterialTheme.typography.headlineMedium, + fontWeight = FontWeight.SemiBold, + ) + Text( + text = "Native Android client for your self-hosted printer control plane.", + style = MaterialTheme.typography.bodyLarge, + ) + OutlinedTextField( + value = draftUrl, + onValueChange = { + draftUrl = it + }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Server URL") }, + placeholder = { Text("https://klipperanywhere.example.com") }, + singleLine = true, + ) + Text( + text = "Use http:// for local testing or https:// for production. The app preserves login sessions and talks directly to the server APIs.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Button(onClick = { + normalizeServerUrl(draftUrl)?.let(onOpen) + }) { + Text("Open server") + } + OutlinedButton(onClick = { + draftUrl = "http://127.0.0.1:8080" + }) { + Text("Local default") + } + } + message?.let { + Text(text = it, color = MaterialTheme.colorScheme.error) + } + } + } + } +} + +@Composable +private fun LoginScreen( + serverUrl: String, + initialUsername: String, + initialRemember: Boolean, + errorMessage: String?, + onUseDifferentServer: () -> Unit, + onForgetSavedAccount: () -> Unit, + onLogin: suspend (String, String, Boolean) -> Boolean, +) { + val scope = rememberCoroutineScope() + var username by rememberSaveable(serverUrl) { mutableStateOf(initialUsername) } + var password by rememberSaveable { mutableStateOf("") } + var rememberCredentials by rememberSaveable(serverUrl) { mutableStateOf(initialRemember) } + var busy by rememberSaveable { mutableStateOf(false) } + var localMessage by rememberSaveable { mutableStateOf(errorMessage) } + LaunchedEffect(errorMessage) { + localMessage = errorMessage + } + LaunchedEffect(initialUsername, initialRemember) { + if (username.isBlank()) { + username = initialUsername + } + rememberCredentials = initialRemember + } + + ScreenFrame( + title = "Sign in", + subtitle = serverUrl, + topActions = { + TextButton(onClick = onUseDifferentServer) { Text("Change server") } + }, + ) { + Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { + Text( + text = "Authenticate with the same account you use on the server.", + style = MaterialTheme.typography.bodyLarge, + ) + OutlinedTextField( + value = username, + onValueChange = { username = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Username") }, + singleLine = true, + ) + OutlinedTextField( + value = password, + onValueChange = { password = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Password") }, + singleLine = true, + ) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Button( + enabled = !busy, + onClick = { + scope.launch { + busy = true + localMessage = null + val ok = onLogin(username.trim(), password, rememberCredentials) + if (!ok) { + localMessage = "Login failed." + } + busy = false + } + }, + ) { + Text(if (busy) "Signing in..." else "Sign in") + } + OutlinedButton( + enabled = !busy, + onClick = { + password = "" + username = "" + rememberCredentials = false + onForgetSavedAccount() + }, + ) { + Text("Forget saved") + } + } + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox( + checked = rememberCredentials, + onCheckedChange = { rememberCredentials = it }, + ) + Text(text = "Remember this account on this device") + } + localMessage?.let { + Text(text = it, color = MaterialTheme.colorScheme.error) + } + } + } +} + +@Composable +private fun AuthenticatedShell( + api: ApiClient, + session: SessionInfo, + serverUrl: String, + screen: Screen, + printerId: String, + webUiUrl: String, + webUiPrinterLabel: String, + onBack: () -> Unit, + onScreenChange: (Screen) -> Unit, + onPrinterChange: (String) -> Unit, + onOpenPrinterUi: (String, String, String, Screen) -> Unit, + onLogout: () -> Unit, + onChangeServer: () -> Unit, +) { + val topLevelItems = buildList { + add(Screen.Dashboard to "Dashboard") + add(Screen.Account to "Account") + if (session.isAdmin) { + add(Screen.Admin to "Admin") + } + } + val isDetailScreen = screen == Screen.PrinterDetail || screen == Screen.PrinterAgent || screen == Screen.PrinterWebUi || screen == Screen.PrinterSettings || screen == Screen.Users || screen == Screen.Audit || screen == Screen.Install + val title = when (screen) { + Screen.Dashboard -> "Dashboard" + Screen.PrinterDetail -> "Printer" + Screen.PrinterAgent -> "Agent" + Screen.PrinterWebUi -> "Printer UI" + Screen.PrinterSettings -> "Printer settings" + Screen.Account -> "Account" + Screen.Admin -> "Admin" + Screen.Users -> "Users" + Screen.Audit -> "Audit" + Screen.Install -> "Install printer" + else -> "KlipperAnywhere" + } + val subtitle = "${session.username} | ${session.role} | $serverUrl" + if (screen == Screen.PrinterWebUi) { + PrinterWebUiScreen( + api = api, + printerId = printerId, + url = webUiUrl, + printerLabel = webUiPrinterLabel, + onBack = onBack, + ) + } else { + Scaffold( + topBar = { + Column { + CenterAlignedTopAppBar( + title = { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text(text = title, fontWeight = FontWeight.SemiBold) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + navigationIcon = { + if (isDetailScreen) { + TextButton(onClick = onBack) { + Text("Back") + } + } else { + TextButton(onClick = onChangeServer) { Text("Server") } + } + }, + actions = { + TextButton(onClick = onLogout) { Text("Sign out") } + }, + ) + HorizontalDivider() + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()) + .padding(horizontal = 12.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + topLevelItems.forEach { (target, label) -> + val selected = screen == target + FilterChip( + selected = selected, + onClick = { onScreenChange(target) }, + label = { Text(label) }, + ) + } + } + HorizontalDivider() + } + }, + ) { padding -> + Box(modifier = Modifier.fillMaxSize().padding(padding)) { + when (screen) { + Screen.Dashboard -> DashboardScreen( + api = api, + session = session, + onOpenPrinter = { + onPrinterChange(it) + onScreenChange(Screen.PrinterDetail) + }, + onOpenSettings = { + onPrinterChange(it) + onScreenChange(Screen.PrinterSettings) + }, + onOpenPrinterUi = { targetPrinterId, label, url -> onOpenPrinterUi(targetPrinterId, label, url, Screen.Dashboard) }, + ) + + Screen.PrinterDetail -> PrinterDetailScreen( + api = api, + session = session, + printerId = printerId, + onOpenSettings = { + onScreenChange(Screen.PrinterSettings) + }, + onOpenAgent = { + onScreenChange(Screen.PrinterAgent) + }, + onOpenPrinterUi = { targetPrinterId, label, url -> onOpenPrinterUi(targetPrinterId, label, url, Screen.PrinterDetail) }, + ) + + Screen.PrinterAgent -> PrinterAgentScreen( + api = api, + session = session, + printerId = printerId, + onBackToPrinter = { onScreenChange(Screen.PrinterDetail) }, + onOpenSettings = { onScreenChange(Screen.PrinterSettings) }, + onOpenInstall = { onScreenChange(Screen.Install) }, + onOpenPrinterUi = { targetPrinterId, label, url -> onOpenPrinterUi(targetPrinterId, label, url, Screen.PrinterAgent) }, + ) + + Screen.PrinterSettings -> PrinterSettingsScreen( + api = api, + session = session, + printerId = printerId, + onBackToPrinter = { onScreenChange(Screen.PrinterDetail) }, + onOpenAgent = { onScreenChange(Screen.PrinterAgent) }, + onOpenInstall = { onScreenChange(Screen.Install) }, + ) + + Screen.Account -> AccountScreen(api = api, session = session) + Screen.Admin -> AdminScreen( + api = api, + session = session, + onOpenUsers = { onScreenChange(Screen.Users) }, + onOpenAudit = { onScreenChange(Screen.Audit) }, + onOpenInstall = { onScreenChange(Screen.Install) }, + onOpenPrinter = { + onPrinterChange(it) + onScreenChange(Screen.PrinterDetail) + }, + onOpenPrinterUi = { targetPrinterId, label, url -> onOpenPrinterUi(targetPrinterId, label, url, Screen.Admin) }, + ) + + Screen.Users -> UsersScreen(api = api, session = session) + Screen.Audit -> AuditScreen(api = api) + Screen.Install -> InstallScreen(api = api, csrfToken = session.csrfToken, printerId = printerId) + else -> DashboardScreen( + api = api, + session = session, + onOpenPrinter = { + onPrinterChange(it) + onScreenChange(Screen.PrinterDetail) + }, + onOpenSettings = { + onPrinterChange(it) + onScreenChange(Screen.PrinterSettings) + }, + onOpenPrinterUi = { targetPrinterId, label, url -> onOpenPrinterUi(targetPrinterId, label, url, Screen.Dashboard) }, + ) + } + } + } + } +} + +@Composable +private fun DashboardScreen( + api: ApiClient, + session: SessionInfo, + onOpenPrinter: (String) -> Unit, + onOpenSettings: (String) -> Unit, + onOpenPrinterUi: (String, String, String) -> Unit, +) { + val context = LocalContext.current + val imageLoader = remember(api) { api.imageLoader(context) } + val scope = rememberCoroutineScope() + var printers by remember { mutableStateOf>(emptyList()) } + var loading by rememberSaveable { mutableStateOf(true) } + var error by rememberSaveable { mutableStateOf(null) } + + LaunchedEffect(Unit) { + loading = true + error = null + printers = api.listPrinters() + loading = false + } + + ScreenBody( + headline = "Connected printers", + subheadline = "Current sessions and agent health from the server.", + ) { + when { + loading -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + printers.isEmpty() -> { + Text(text = error ?: "No printers are connected right now.") + } + else -> { + val pullRefreshState = rememberPullRefreshState( + refreshing = loading, + onRefresh = { + scope.launch { + loading = true + printers = api.listPrinters() + loading = false + } + }, + ) + Box( + modifier = Modifier + .fillMaxSize() + .pullRefresh(pullRefreshState), + ) { + LazyColumn(verticalArrangement = Arrangement.spacedBy(12.dp)) { + items(printers, key = { it.printerId }) { printer -> + PrinterSummaryCard( + api = api, + imageLoader = imageLoader, + printer = printer, + isAdmin = session.isAdmin, + onOpenPrinter = { onOpenPrinter(printer.printerId) }, + onOpenSettings = { onOpenSettings(printer.printerId) }, + onOpenPrinterUi = onOpenPrinterUi, + ) + } + } + PullRefreshIndicator( + refreshing = loading, + state = pullRefreshState, + modifier = Modifier.align(Alignment.TopCenter), + ) + } + } + } + } +} + +@Composable +private fun PrinterSummaryCard( + api: ApiClient, + imageLoader: coil.ImageLoader, + printer: PrinterSummary, + isAdmin: Boolean, + onOpenPrinter: () -> Unit, + onOpenSettings: () -> Unit, + onOpenPrinterUi: (String, String, String) -> Unit, +) { + val health = printer.health + val settings = printer.settings + val camera = health?.cameras?.firstOrNull { it.hasSnapshot } + val snapshotUrl = camera?.let { api.requestPrinterSnapshotUrl(printer.printerId, it.name) } + Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)) { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Column(modifier = Modifier.weight(1f)) { + Text(text = settings.displayName ?: printer.printerId, fontWeight = FontWeight.SemiBold) + if (!settings.displayName.isNullOrBlank() && settings.displayName != printer.printerId) { + Text(text = printer.printerId, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + StatusPill(text = if (printer.connected) "Connected" else "Disconnected", ok = printer.connected) + } + + if (snapshotUrl != null) { + AsyncImage( + model = snapshotUrl, + contentDescription = "${printer.printerId} snapshot", + imageLoader = imageLoader, + modifier = Modifier + .fillMaxWidth() + .height(180.dp) + .clip(MaterialTheme.shapes.medium), + ) + } + + FactGrid( + facts = buildList { + add("Moonraker" to (health?.moonrakerState ?: "Unknown")) + add("Message" to (health?.moonrakerMessage ?: "No status yet")) + add("Last heartbeat" to formatRelativeTime(health?.checkedAtUnix)) + temperatureSummaryText(health?.printStatus)?.let { add("Temps" to it) } + }, + ) + val mmuFacts = mmuMaterialFacts(health?.printStatus) + if (mmuFacts.isNotEmpty()) { + Text(text = "MMU materials", fontWeight = FontWeight.SemiBold) + MmuMaterialSection(facts = mmuFacts) + } + + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) { + Button(onClick = onOpenPrinter) { Text("Open") } + if (isAdmin) { + OutlinedButton(onClick = onOpenSettings) { Text("Settings") } + } + if (health?.uiReachable == true) { + OutlinedButton(onClick = { onOpenPrinterUi(printer.printerId, printer.settings.displayName ?: printer.printerId, printerUiTargetUrl(api, printer.printerId)) }) { + Text("Open UI") + } + } + } + } + } +} + +@Composable +private fun PrinterDetailScreen( + api: ApiClient, + session: SessionInfo, + printerId: String, + onOpenSettings: () -> Unit, + onOpenAgent: () -> Unit, + onOpenPrinterUi: (String, String, String) -> Unit, +) { + val context = LocalContext.current + val imageLoader = remember(api) { api.imageLoader(context) } + val scope = rememberCoroutineScope() + var detail by remember { mutableStateOf(null) } + var loading by rememberSaveable { mutableStateOf(true) } + var message by rememberSaveable { mutableStateOf(null) } + var refreshToken by rememberSaveable { mutableStateOf(0) } + + suspend fun reload() { + loading = true + message = null + detail = api.getPrinter(printerId) + loading = false + } + + LaunchedEffect(printerId, refreshToken) { + reload() + } + + ScreenBody( + headline = detail?.settings?.displayName ?: printerId, + subheadline = "Printer detail and live status.", + scrollable = true, + refreshing = loading, + onRefresh = { refreshToken++ }, + trailing = { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (session.isAdmin) { + TextButton(onClick = onOpenSettings) { Text("Settings") } + } + } + }, + ) { + when { + loading -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + detail == null -> Text(text = "Unable to load printer.") + else -> { + val d = detail!! + Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + Column(modifier = Modifier.weight(1f)) { + Text(text = d.settings.displayName ?: printerId, fontWeight = FontWeight.SemiBold) + Text(text = printerId, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + StatusPill(text = d.health?.moonrakerState ?: if (d.connected) "Connected" else "Offline", ok = d.connected && d.health?.moonrakerReachable == true) + } + FactGrid( + facts = listOf( + "Agent" to (d.health?.agentVersion ?: "Unknown"), + "Host" to (d.health?.hostname ?: "Unknown"), + "Control mode" to (d.controlMode ?: "readonly"), + "Access" to (d.access ?: "unknown"), + "Sync" to (d.settingsSyncState ?: "Pending"), + "Sync detail" to (d.settingsSyncDetail ?: "Waiting"), + ), + ) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Button(onClick = { onOpenPrinterUi(printerId, d.settings.displayName ?: printerId, api.printerUiUrl(printerId)) }) { Text("Open UI") } + OutlinedButton(onClick = onOpenAgent) { Text("Agent") } + OutlinedButton(onClick = { onOpenPrinterUi(printerId, d.settings.displayName ?: printerId, api.printerInfoUrl(printerId)) }) { Text("Info JSON") } + OutlinedButton(onClick = { onOpenPrinterUi(printerId, d.settings.displayName ?: printerId, api.printerHealthUrl(printerId)) }) { Text("Health JSON") } + } + } + } + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Moonraker info", fontWeight = FontWeight.SemiBold) + FactGrid( + facts = listOf( + "Hostname" to (d.info?.hostname ?: "Unknown"), + "Software" to (d.info?.softwareVersion ?: "Unknown"), + "CPU" to (d.info?.cpuInfo ?: "Unknown"), + "Config" to (d.info?.configFile ?: "Unknown"), + "Log" to (d.info?.logFile ?: "Unknown"), + ), + ) + } + } + + val detailPrintStatus = d.health?.printStatus ?: d.printStatus + val printerTemperatureFacts = temperatureFacts(detailPrintStatus) + if (printerTemperatureFacts.isNotEmpty()) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Temperatures", fontWeight = FontWeight.SemiBold) + FactGrid(facts = printerTemperatureFacts) + } + } + } + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Print status", fontWeight = FontWeight.SemiBold) + FactGrid( + facts = buildList { + add("State" to (d.printStatus?.state ?: "Unknown")) + add("File" to (d.printStatus?.filename ?: "No file loaded")) + add("Progress" to formatPercent(d.printStatus?.progress)) + add("Duration" to formatDuration(d.printStatus?.printDuration)) + add("Total" to formatDuration(d.printStatus?.totalDuration)) + add("Remaining" to formatDuration(d.printStatus?.estimatedRemaining)) + add("Filament" to formatFilament(d.printStatus?.filamentUsed)) + add("Message" to (d.printStatus?.message ?: "No status message yet")) + temperatureSummaryText(detailPrintStatus)?.let { add("Temps" to it) } + }, + ) + if (d.controlMode == "full") { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Button(onClick = { + scope.launch { + val result = api.postText("/p/${printerId.encodePathSegment()}/moonraker/printer/print/pause", "{}") + message = if (result.first in 200..299) "Pause sent." else result.second.ifBlank { "Pause failed." } + refreshToken++ + } + }) { Text("Pause") } + Button(onClick = { + scope.launch { + val result = api.postText("/p/${printerId.encodePathSegment()}/moonraker/printer/print/resume", "{}") + message = if (result.first in 200..299) "Resume sent." else result.second.ifBlank { "Resume failed." } + refreshToken++ + } + }) { Text("Resume") } + OutlinedButton(onClick = { + scope.launch { + val result = api.postText("/p/${printerId.encodePathSegment()}/moonraker/printer/print/cancel", "{}") + message = if (result.first in 200..299) "Cancel sent." else result.second.ifBlank { "Cancel failed." } + refreshToken++ + } + }) { Text("Cancel") } + } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + OutlinedButton(onClick = { + scope.launch { + val result = api.postText("/p/${printerId.encodePathSegment()}/moonraker/printer/emergency_stop", "{}") + message = if (result.first in 200..299) "Emergency stop sent." else result.second.ifBlank { "Emergency stop failed." } + refreshToken++ + } + }) { Text("Emergency stop") } + } + } else { + Text(text = "Control mode is read-only on this server.") + } + } + } + + val mmuFacts = mmuMaterialFacts(detailPrintStatus) + if (mmuFacts.isNotEmpty()) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "MMU materials", fontWeight = FontWeight.SemiBold) + MmuMaterialSection(facts = mmuFacts) + } + } + } + + CameraSection( + api = api, + imageLoader = imageLoader, + printerId = printerId, + printerLabel = d.settings.displayName ?: printerId, + cameras = d.health?.cameras.orEmpty(), + onOpenPrinterUi = onOpenPrinterUi, + ) + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Recent jobs", fontWeight = FontWeight.SemiBold) + if (d.recentJobs.isEmpty()) { + Text(text = "No recent jobs found.") + } else { + d.recentJobs.forEach { job -> + JobRow(job = job) + HorizontalDivider() + } + } + } + } + message?.let { Text(text = it, color = MaterialTheme.colorScheme.primary) } + } + } + } + } +} + +@Composable +private fun PrinterAgentScreen( + api: ApiClient, + session: SessionInfo, + printerId: String, + onBackToPrinter: () -> Unit, + onOpenSettings: () -> Unit, + onOpenInstall: () -> Unit, + onOpenPrinterUi: (String, String, String) -> Unit, +) { + val context = LocalContext.current + val imageLoader = remember(api) { api.imageLoader(context) } + val scope = rememberCoroutineScope() + var detail by remember { mutableStateOf(null) } + var loading by rememberSaveable { mutableStateOf(true) } + var message by rememberSaveable { mutableStateOf(null) } + var refreshToken by rememberSaveable { mutableStateOf(0) } + + suspend fun reload() { + loading = true + message = null + detail = api.getPrinter(printerId) + loading = false + } + + LaunchedEffect(printerId, refreshToken) { + reload() + } + + ScreenBody( + headline = detail?.settings?.displayName ?: printerId, + subheadline = "Printer agent health, UI, sync, and update controls.", + scrollable = true, + refreshing = loading, + onRefresh = { refreshToken++ }, + trailing = { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + TextButton(onClick = onBackToPrinter) { Text("Printer") } + if (session.isAdmin) { + TextButton(onClick = onOpenSettings) { Text("Settings") } + } + TextButton(onClick = onOpenInstall) { Text("Install") } + } + }, + ) { + when { + loading -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + detail == null -> Text(text = "Unable to load printer agent.") + else -> { + val d = detail!! + val health = d.health + val settings = d.settings + val install = settings.install + Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Agent", fontWeight = FontWeight.SemiBold) + FactGrid( + facts = listOf( + "Printer ID" to printerId, + "Agent version" to (health?.agentVersion ?: "Unknown"), + "Hostname" to (health?.hostname ?: "Unknown"), + "Connected" to if (d.connected) "Yes" else "No", + "Moonraker" to (health?.moonrakerState ?: "Unknown"), + "Moonraker message" to (health?.moonrakerMessage ?: "No status message yet"), + "Last heartbeat" to formatRelativeTime(health?.checkedAtUnix), + "Access" to (d.access ?: "unknown"), + ), + ) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Button(onClick = { onOpenPrinterUi(printerId, d.settings.displayName ?: printerId, api.printerHealthUrl(printerId)) }) { Text("Health JSON") } + OutlinedButton(onClick = { onOpenPrinterUi(printerId, d.settings.displayName ?: printerId, api.printerInfoUrl(printerId)) }) { Text("Info JSON") } + OutlinedButton(onClick = { onOpenPrinterUi(printerId, d.settings.displayName ?: printerId, printerUiTargetUrl(api, printerId)) }) { Text("Open UI") } + } + } + } + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Connectivity", fontWeight = FontWeight.SemiBold) + FactGrid( + facts = listOf( + "Moonraker reachable" to if (health?.moonrakerReachable == true) "Yes" else "No", + "UI reachable" to if (health?.uiReachable == true) "Yes" else "No", + "UI source" to (health?.uiSource ?: "Unknown"), + "Applied UI URL" to (health?.uiUrl ?: "Unset"), + "Auto-detect" to if (health?.uiAutoDetect == true) "On" else "Off", + "Camera count" to (health?.cameras?.size?.toString() ?: "0"), + ), + ) + } + } + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Settings sync", fontWeight = FontWeight.SemiBold) + FactGrid( + facts = listOf( + "Control mode" to (d.controlMode ?: "readonly"), + "Applied mode" to (health?.controlMode ?: "Unknown"), + "Settings synced" to if (d.settingsSynced) "Yes" else "No", + "Sync state" to (d.settingsSyncState ?: "Pending"), + "Sync detail" to (d.settingsSyncDetail ?: "Waiting"), + "Updated" to (settings.updatedAt ?: "Unknown"), + "Last synced" to (settings.lastSyncedAt ?: "Unknown"), + ), + ) + } + } + + if (install != null) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Install details", fontWeight = FontWeight.SemiBold) + FactGrid( + facts = listOf( + "Status" to (install.status ?: "unknown"), + "Host type" to (install.hostType ?: "standard"), + "Server URL" to (install.serverUrl ?: "Unknown"), + "Moonraker URL" to (install.moonrakerUrl ?: "Unknown"), + "UI URL" to (install.uiUrl ?: "Auto"), + "Binary source" to (install.binarySource ?: "Unknown"), + "Message" to (install.message ?: "No install message."), + ), + ) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Button(onClick = onOpenInstall) { Text("Reinstall via SSH") } + if (session.isAdmin) { + OutlinedButton(onClick = { + scope.launch { + message = if (api.triggerAgentUpdate(printerId, session.csrfToken) != null) { + refreshToken++ + "Agent update requested." + } else { + "Unable to request agent update." + } + } + }) { Text("Upgrade now") } + } + } + } + } + } + + CameraSection( + api = api, + imageLoader = imageLoader, + printerId = printerId, + printerLabel = d.settings.displayName ?: printerId, + cameras = health?.cameras.orEmpty(), + onOpenPrinterUi = onOpenPrinterUi, + ) + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Recent jobs", fontWeight = FontWeight.SemiBold) + if (d.recentJobs.isEmpty()) { + Text(text = "No recent jobs found.") + } else { + d.recentJobs.forEach { job -> + JobRow(job = job) + HorizontalDivider() + } + } + } + } + message?.let { Text(text = it, color = MaterialTheme.colorScheme.primary) } + } + } + } + } +} + +@Composable +private fun CameraSection( + api: ApiClient, + imageLoader: coil.ImageLoader, + printerId: String, + printerLabel: String, + cameras: List, + onOpenPrinterUi: (String, String, String) -> Unit, +) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Cameras", fontWeight = FontWeight.SemiBold) + if (cameras.isEmpty()) { + Text(text = "No cameras are configured for this printer.") + } else { + cameras.forEach { camera -> + val snapshotUrl = api.requestPrinterSnapshotUrl(printerId, camera.name) + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text(text = camera.name, fontWeight = FontWeight.Medium) + if (camera.hasSnapshot) { + AsyncImage( + model = "$snapshotUrl?t=${System.currentTimeMillis()}", + contentDescription = camera.name, + imageLoader = imageLoader, + modifier = Modifier + .fillMaxWidth() + .height(200.dp) + .clip(MaterialTheme.shapes.medium), + ) + } else { + Text(text = "No snapshot available.") + } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + if (camera.hasStream) { + OutlinedButton(onClick = { onOpenPrinterUi(printerId, printerLabel, api.requestPrinterStreamUrl(printerId, camera.name)) }) { + Text("Open stream") + } + } + if (camera.hasSnapshot) { + OutlinedButton(onClick = { onOpenPrinterUi(printerId, printerLabel, snapshotUrl) }) { Text("Snapshot") } + } + } + FactGrid( + facts = listOf( + "Aspect" to (camera.aspectRatio ?: "16:9"), + "Rotation" to (camera.rotation?.toString() ?: "0"), + "Location" to (camera.location ?: "Unknown"), + "Service" to (camera.service ?: "Unknown"), + "Source" to (camera.source ?: "Unknown"), + ), + ) + } + if (camera != cameras.last()) { + HorizontalDivider() + } + } + } + } + } +} + +@Composable +private fun PrinterSettingsScreen( + api: ApiClient, + session: SessionInfo, + printerId: String, + onBackToPrinter: () -> Unit, + onOpenAgent: () -> Unit, + onOpenInstall: () -> Unit, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + var settings by remember { mutableStateOf(null) } + var health by remember { mutableStateOf(null) } + var loading by rememberSaveable { mutableStateOf(true) } + var message by rememberSaveable { mutableStateOf(null) } + var displayName by rememberSaveable { mutableStateOf("") } + var refreshToken by rememberSaveable { mutableStateOf(0) } + var controlMode by rememberSaveable { mutableStateOf("readonly") } + var uiUrl by rememberSaveable { mutableStateOf("") } + var uiAutoDetect by rememberSaveable { mutableStateOf(true) } + var uiLaunchMode by rememberSaveable { mutableStateOf(PrinterUiLaunchMode.Embedded) } + var uiLaunchModeMenuExpanded by rememberSaveable { mutableStateOf(false) } + var notifyEnabled by rememberSaveable { mutableStateOf(false) } + var notifyStarted by rememberSaveable { mutableStateOf(false) } + var notifyPaused by rememberSaveable { mutableStateOf(false) } + var notifyResumed by rememberSaveable { mutableStateOf(false) } + var notifyCompleted by rememberSaveable { mutableStateOf(false) } + var notifyCanceled by rememberSaveable { mutableStateOf(false) } + var notifyFailed by rememberSaveable { mutableStateOf(false) } + var notifyFirstLayer by rememberSaveable { mutableStateOf(false) } + var notifyThirdLayer by rememberSaveable { mutableStateOf(false) } + var notificationCamera by rememberSaveable { mutableStateOf("") } + var notificationCameraMenuExpanded by rememberSaveable { mutableStateOf(false) } + + LaunchedEffect(printerId, api.baseUrlString()) { + loading = true + val detail = api.getPrinter(printerId) + uiLaunchMode = resolvePrinterUiLaunchMode(context, api.baseUrlString(), printerId) + settings = detail?.settings + health = detail?.health + detail?.settings?.let { + displayName = it.displayName.orEmpty() + controlMode = it.controlMode ?: "readonly" + uiUrl = it.uiUrl.orEmpty() + uiAutoDetect = it.uiAutoDetect + notifyEnabled = it.printNotificationsEnabled + notifyStarted = it.notifyPrintStarted + notifyPaused = it.notifyPrintPaused + notifyResumed = it.notifyPrintResumed + notifyCompleted = it.notifyPrintCompleted + notifyCanceled = it.notifyPrintCanceled + notifyFailed = it.notifyPrintFailed + notifyFirstLayer = it.notifyFirstLayer + notifyThirdLayer = it.notifyThirdLayer + notificationCamera = it.notificationSnapshotCamera.orEmpty() + } + loading = false + } + + ScreenBody( + headline = settings?.displayName ?: printerId, + subheadline = "Rename the printer for the UI and keep the agent sync settings in one place.", + scrollable = true, + refreshing = loading, + onRefresh = { refreshToken++ }, + trailing = { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + TextButton(onClick = onBackToPrinter) { Text("Back") } + TextButton(onClick = onOpenAgent) { Text("Agent") } + TextButton(onClick = onOpenInstall) { Text("Upgrade agent") } + } + }, + ) { + when { + loading -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + else -> Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Identity", fontWeight = FontWeight.SemiBold) + FactGrid( + facts = listOf( + "Printer ID" to printerId, + "Display name" to (settings?.displayName ?: "Not set"), + "Agent hostname" to (health?.hostname ?: "Unknown"), + "Agent version" to (health?.agentVersion ?: "Unknown"), + "Moonraker" to (health?.moonrakerState ?: "Unknown"), + "UI source" to (health?.uiSource ?: "Unknown"), + ), + ) + } + } + + if (session.isAdmin) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Editable settings", fontWeight = FontWeight.SemiBold) + OutlinedTextField( + value = displayName, + onValueChange = { displayName = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Display name") }, + ) + OutlinedTextField( + value = controlMode, + onValueChange = { controlMode = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Control mode (readonly/full)") }, + ) + OutlinedTextField( + value = uiUrl, + onValueChange = { uiUrl = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("UI URL") }, + ) + val uiLaunchModeLabel = printerUiLaunchModeLabel(uiLaunchMode) + Box { + OutlinedButton( + onClick = { uiLaunchModeMenuExpanded = true }, + modifier = Modifier.fillMaxWidth(), + ) { + Text("Printer UI mode: $uiLaunchModeLabel") + } + DropdownMenu( + expanded = uiLaunchModeMenuExpanded, + onDismissRequest = { uiLaunchModeMenuExpanded = false }, + ) { + PrinterUiLaunchMode.values().forEach { mode -> + DropdownMenuItem( + text = { Text(printerUiLaunchModeLabel(mode)) }, + onClick = { + uiLaunchMode = mode + savePrinterUiLaunchMode(context, api.baseUrlString(), printerId, mode) + uiLaunchModeMenuExpanded = false + }, + ) + } + } + } + Text( + text = "Choose whether this printer opens inside the app or in the browser.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Row(verticalAlignment = Alignment.CenterVertically) { + Switch(checked = uiAutoDetect, onCheckedChange = { uiAutoDetect = it }) + Text(text = "Auto-detect UI on the host") + } + Text(text = "Print notifications", fontWeight = FontWeight.Medium) + Row(verticalAlignment = Alignment.CenterVertically) { + Switch(checked = notifyEnabled, onCheckedChange = { notifyEnabled = it }) + Text(text = "Enable print notifications") + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Switch(checked = notifyStarted, onCheckedChange = { notifyStarted = it }) + Text(text = "Print started") + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Switch(checked = notifyPaused, onCheckedChange = { notifyPaused = it }) + Text(text = "Print paused") + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Switch(checked = notifyResumed, onCheckedChange = { notifyResumed = it }) + Text(text = "Print resumed") + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Switch(checked = notifyCompleted, onCheckedChange = { notifyCompleted = it }) + Text(text = "Print completed") + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Switch(checked = notifyCanceled, onCheckedChange = { notifyCanceled = it }) + Text(text = "Print canceled") + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Switch(checked = notifyFailed, onCheckedChange = { notifyFailed = it }) + Text(text = "Print failed") + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Switch(checked = notifyFirstLayer, onCheckedChange = { notifyFirstLayer = it }) + Text(text = "First layer") + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Switch(checked = notifyThirdLayer, onCheckedChange = { notifyThirdLayer = it }) + Text(text = "Third layer") + } + val snapshotCameras = health?.cameras.orEmpty().filter { it.hasSnapshot } + val selectedCameraLabel = when { + notificationCamera.isBlank() -> "First snapshot-capable camera" + snapshotCameras.any { it.name == notificationCamera } -> notificationCamera + else -> "$notificationCamera (unavailable)" + } + Box { + OutlinedButton( + onClick = { notificationCameraMenuExpanded = true }, + modifier = Modifier.fillMaxWidth(), + ) { + Text("Notification snapshot camera: $selectedCameraLabel") + } + DropdownMenu( + expanded = notificationCameraMenuExpanded, + onDismissRequest = { notificationCameraMenuExpanded = false }, + ) { + DropdownMenuItem( + text = { Text("First snapshot-capable camera") }, + onClick = { + notificationCamera = "" + notificationCameraMenuExpanded = false + }, + ) + snapshotCameras.forEach { camera -> + DropdownMenuItem( + text = { Text(camera.name) }, + onClick = { + notificationCamera = camera.name + notificationCameraMenuExpanded = false + }, + ) + } + if (notificationCamera.isNotBlank() && snapshotCameras.none { it.name == notificationCamera }) { + DropdownMenuItem( + text = { Text("$notificationCamera (unavailable)") }, + onClick = { + notificationCameraMenuExpanded = false + }, + ) + } + } + } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Button(onClick = { + scope.launch { + val body = JSONObject() + .put("display_name", displayName) + .put("control_mode", controlMode) + .put("ui_url", uiUrl) + .put("ui_auto_detect", uiAutoDetect) + .put("print_notifications_enabled", notifyEnabled) + .put("notify_print_started", notifyStarted) + .put("notify_print_paused", notifyPaused) + .put("notify_print_resumed", notifyResumed) + .put("notify_print_completed", notifyCompleted) + .put("notify_print_canceled", notifyCanceled) + .put("notify_print_failed", notifyFailed) + .put("notify_print_first_layer", notifyFirstLayer) + .put("notify_print_third_layer", notifyThirdLayer) + .put("notification_snapshot_camera", notificationCamera) + val ok = api.patchText( + "/api/printers/${printerId.encodePathSegment()}/settings", + body.toString(), + session.csrfToken, + ) + message = if (ok.first in 200..299) "Settings saved." else ok.second.ifBlank { "Failed to save settings." } + if (ok.first in 200..299) { + val refreshed = api.getPrinter(printerId) + settings = refreshed?.settings + health = refreshed?.health + } + } + }) { Text("Save settings") } + OutlinedButton(onClick = onOpenInstall) { Text("Upgrade agent") } + } + message?.let { Text(text = it) } + } + } + } + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Agent applied", fontWeight = FontWeight.SemiBold) + FactGrid( + facts = listOf( + "Applied mode" to (health?.controlMode ?: "Unknown"), + "Applied UI URL" to (health?.uiUrl ?: "Unset"), + "UI reachable" to if (health?.uiReachable == true) "Yes" else "No", + "Last heartbeat" to formatRelativeTime(health?.checkedAtUnix), + "Current agent" to (health?.agentVersion ?: "Unknown"), + "Available agent" to (session.serverVersion.ifBlank { "Unknown" }), + ), + ) + } + } + } + } + } +} + +@Composable +private fun PrinterWebUiScreen( + api: ApiClient, + printerId: String, + url: String, + printerLabel: String, + onBack: () -> Unit, +) { + val context = LocalContext.current + val targetUrl = remember(url) { url.trim() } + var loading by rememberSaveable(targetUrl) { mutableStateOf(true) } + var error by rememberSaveable(targetUrl) { mutableStateOf(null) } + var webView by remember { mutableStateOf(null) } + var refreshLayout by remember { mutableStateOf(null) } + var canGoBack by remember { mutableStateOf(false) } + var loadedTargetUrl by remember(targetUrl) { mutableStateOf(null) } + + fun navigateBack() { + val currentWebView = webView + if (currentWebView?.canGoBack() == true) { + currentWebView.goBack() + } else { + onBack() + } + } + + DisposableEffect(Unit) { + onDispose { + webView?.destroy() + webView = null + } + } + + BackHandler { + navigateBack() + } + + Column(modifier = Modifier.fillMaxSize()) { + Surface( + tonalElevation = 2.dp, + shadowElevation = 1.dp, + modifier = Modifier.fillMaxWidth(), + ) { + Column( + modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = printerLabel.ifBlank { printerId }, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = printerId, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + TextButton(onClick = { openExternal(context, targetUrl) }) { Text("Browser") } + TextButton(onClick = { navigateBack() }) { Text("Close") } + } + } + if (loading) { + LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + } + error?.let { + Text( + text = it, + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall, + ) + } + } + } + Box( + modifier = Modifier + .fillMaxWidth() + .weight(1f), + ) { + when { + targetUrl.isBlank() -> { + Text( + text = "No printer UI URL available.", + modifier = Modifier.align(Alignment.Center), + ) + } + else -> { + AndroidView( + factory = { viewContext -> + SwipeRefreshLayout(viewContext).apply { + refreshLayout = this + setOnRefreshListener { + webView?.reload() + } + addView( + WebView(viewContext).apply { + webView = this + settings.javaScriptEnabled = true + settings.domStorageEnabled = true + settings.loadWithOverviewMode = true + settings.useWideViewPort = true + settings.builtInZoomControls = true + settings.displayZoomControls = false + settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE + webViewClient = object : WebViewClient() { + override fun onPageStarted(view: WebView?, pageUrl: String?, favicon: android.graphics.Bitmap?) { + loading = true + error = null + canGoBack = view?.canGoBack() == true + } + + override fun onPageFinished(view: WebView?, pageUrl: String?) { + loading = false + canGoBack = view?.canGoBack() == true + refreshLayout?.isRefreshing = false + } + + override fun onReceivedError( + view: WebView?, + request: WebResourceRequest?, + webError: WebResourceError?, + ) { + if (request?.isForMainFrame != false) { + loading = false + error = webError?.description?.toString() ?: "Unable to load printer UI." + refreshLayout?.isRefreshing = false + } + } + + override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { + val uri = request?.url ?: return false + return when (uri.scheme?.lowercase()) { + "http", "https" -> false + else -> { + openExternal(context, uri.toString()) + true + } + } + } + } + webChromeClient = object : WebChromeClient() { + override fun onProgressChanged(view: WebView?, newProgress: Int) { + loading = newProgress < 100 + canGoBack = view?.canGoBack() == true + refreshLayout?.isRefreshing = loading + } + } + }, + android.view.ViewGroup.LayoutParams( + android.view.ViewGroup.LayoutParams.MATCH_PARENT, + android.view.ViewGroup.LayoutParams.MATCH_PARENT, + ), + ) + } + }, + update = { view -> + refreshLayout = view + view.isRefreshing = loading + webView = view.getChildAt(0) as? WebView ?: webView + canGoBack = webView?.canGoBack() == true + }, + modifier = Modifier.fillMaxSize(), + ) + } + } + } + } + + LaunchedEffect(targetUrl, webView) { + val currentWebView = webView ?: return@LaunchedEffect + if (targetUrl.isBlank() || loadedTargetUrl == targetUrl) { + return@LaunchedEffect + } + loading = true + error = null + syncPrinterUiCookies(api, printerId, currentWebView) { + currentWebView.loadUrl(targetUrl) + loadedTargetUrl = targetUrl + } + } +} + +@Composable +private fun AccountScreen(api: ApiClient, session: SessionInfo) { + val scope = rememberCoroutineScope() + var currentPassword by rememberSaveable { mutableStateOf("") } + var newPassword by rememberSaveable { mutableStateOf("") } + var confirmPassword by rememberSaveable { mutableStateOf("") } + var message by rememberSaveable { mutableStateOf(null) } + + ScreenBody(headline = "Account", subheadline = "Manage your KlipperAnywhere account.", scrollable = true) { + Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + FactGrid( + facts = listOf( + "Username" to session.username, + "Role" to session.role, + "Printer grants" to if (session.printerGrants.isEmpty()) "No printer access assigned." else session.printerGrants.joinToString("\n") { "${it.printerId}:${it.access}" }, + ), + ) + } + } + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Change password", fontWeight = FontWeight.SemiBold) + OutlinedTextField( + value = currentPassword, + onValueChange = { currentPassword = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Current password") }, + singleLine = true, + ) + OutlinedTextField( + value = newPassword, + onValueChange = { newPassword = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("New password") }, + singleLine = true, + ) + OutlinedTextField( + value = confirmPassword, + onValueChange = { confirmPassword = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Confirm new password") }, + singleLine = true, + ) + Button(onClick = { + scope.launch { + message = if (newPassword != confirmPassword) { + "New passwords do not match." + } else if (api.updateAccount(currentPassword, newPassword, session.csrfToken)) { + currentPassword = "" + newPassword = "" + confirmPassword = "" + "Password updated." + } else { + "Unable to update password." + } + } + }) { Text("Update password") } + message?.let { Text(text = it) } + } + } + } + } +} + +@Composable +private fun AdminScreen( + api: ApiClient, + session: SessionInfo, + onOpenUsers: () -> Unit, + onOpenAudit: () -> Unit, + onOpenInstall: () -> Unit, + onOpenPrinter: (String) -> Unit, + onOpenPrinterUi: (String, String, String) -> Unit, +) { + val scope = rememberCoroutineScope() + var notifications by remember { mutableStateOf(null) } + var printers by remember { mutableStateOf>(emptyList()) } + var telegramEnabled by rememberSaveable { mutableStateOf(false) } + var telegramCommandsEnabled by rememberSaveable { mutableStateOf(false) } + var telegramBotToken by rememberSaveable { mutableStateOf("") } + var telegramChatId by rememberSaveable { mutableStateOf("") } + var message by rememberSaveable { mutableStateOf(null) } + var loading by rememberSaveable { mutableStateOf(true) } + + suspend fun reload() { + loading = true + notifications = api.getNotifications() + printers = api.listPrinters() + notifications?.let { + telegramEnabled = it.telegramEnabled + telegramCommandsEnabled = it.telegramCommandsEnabled + telegramBotToken = it.telegramBotToken.orEmpty() + telegramChatId = it.telegramChatId.orEmpty() + } + loading = false + } + + LaunchedEffect(Unit) { + reload() + } + + ScreenBody( + headline = "Admin", + subheadline = "Manage printer installs, users, and audit history from one place.", + scrollable = true, + refreshing = loading, + onRefresh = { scope.launch { reload() } }, + ) { + Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Admin tools", fontWeight = FontWeight.SemiBold) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Button(onClick = onOpenInstall) { Text("Open installer") } + OutlinedButton(onClick = onOpenUsers) { Text("Users") } + OutlinedButton(onClick = onOpenAudit) { Text("Audit") } + } + } + } + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Telegram notifications", fontWeight = FontWeight.SemiBold) + Row(verticalAlignment = Alignment.CenterVertically) { + Switch(checked = telegramEnabled, onCheckedChange = { telegramEnabled = it }) + Text(text = "Enable Telegram delivery") + } + Row(verticalAlignment = Alignment.CenterVertically) { + Switch(checked = telegramCommandsEnabled, onCheckedChange = { telegramCommandsEnabled = it }) + Text(text = "Enable Telegram bot commands") + } + OutlinedTextField( + value = telegramBotToken, + onValueChange = { telegramBotToken = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Telegram bot token") }, + ) + OutlinedTextField( + value = telegramChatId, + onValueChange = { telegramChatId = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Telegram chat ID") }, + ) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Button(onClick = { + scope.launch { + val body = JSONObject() + .put("telegram_enabled", telegramEnabled) + .put("telegram_commands_enabled", telegramCommandsEnabled) + .put("telegram_chat_id", telegramChatId) + if (telegramBotToken.isNotBlank()) { + body.put("telegram_bot_token", telegramBotToken) + } + val updated = api.updateNotifications(body, session.csrfToken) + notifications = updated + message = if (updated != null) "Telegram settings saved." else "Unable to save Telegram settings." + } + }) { Text("Save") } + OutlinedButton(onClick = { + scope.launch { + val body = JSONObject() + .put("telegram_enabled", telegramEnabled) + .put("telegram_chat_id", telegramChatId) + if (telegramBotToken.isNotBlank()) { + body.put("telegram_bot_token", telegramBotToken) + } + message = api.testNotifications(body, session.csrfToken) ?: "Unable to send test notification." + } + }) { Text("Test notification") } + } + message?.let { Text(text = it) } + } + } + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Connected printers", fontWeight = FontWeight.SemiBold) + if (printers.isEmpty()) { + Text(text = "No printers are connected right now.") + } else { + printers.forEach { printer -> + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Column(modifier = Modifier.weight(1f)) { + Text(text = printer.settings.displayName ?: printer.printerId, fontWeight = FontWeight.Medium) + Text(text = printer.printerId, style = MaterialTheme.typography.bodySmall) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton(onClick = { onOpenPrinter(printer.printerId) }) { Text("Open") } + Button(onClick = onOpenInstall) { Text("Upgrade") } + OutlinedButton(onClick = { onOpenPrinterUi(printer.printerId, printer.settings.displayName ?: printer.printerId, printerUiTargetUrl(api, printer.printerId)) }) { Text("UI") } + } + } + if (printer != printers.last()) { + HorizontalDivider() + } + } + } + } + } + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text(text = "Versions", fontWeight = FontWeight.SemiBold) + FactGrid( + facts = listOf( + "Server build" to session.serverVersion, + "Available agent" to session.serverVersion, + ), + ) + } + } + } + } +} + +@Composable +private fun UsersScreen(api: ApiClient, session: SessionInfo) { + val scope = rememberCoroutineScope() + var users by remember { mutableStateOf>(emptyList()) } + var createUsername by rememberSaveable { mutableStateOf("") } + var createPassword by rememberSaveable { mutableStateOf("") } + var createRole by rememberSaveable { mutableStateOf("user") } + var createGrants by rememberSaveable { mutableStateOf("") } + var message by rememberSaveable { mutableStateOf(null) } + var loading by rememberSaveable { mutableStateOf(true) } + + LaunchedEffect(Unit) { + loading = true + users = api.listUsers() + loading = false + } + + ScreenBody( + headline = "Users", + subheadline = "Create another login for family members or shared access on the same printer server.", + scrollable = true, + refreshing = loading, + onRefresh = { + scope.launch { + loading = true + users = api.listUsers() + loading = false + } + }, + ) { + Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Add user", fontWeight = FontWeight.SemiBold) + OutlinedTextField( + value = createUsername, + onValueChange = { createUsername = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Username") }, + ) + OutlinedTextField( + value = createPassword, + onValueChange = { createPassword = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Password") }, + ) + OutlinedTextField( + value = createRole, + onValueChange = { createRole = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Role") }, + ) + OutlinedTextField( + value = createGrants, + onValueChange = { createGrants = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Printer grants") }, + minLines = 3, + ) + Button(onClick = { + scope.launch { + val payload = JSONObject() + .put("username", createUsername) + .put("password", createPassword) + .put("role", createRole) + .put("printer_grants", printerGrantsToJson(createGrants)) + if (api.createUser(payload, session.csrfToken)) { + users = api.listUsers() + createUsername = "" + createPassword = "" + createRole = "user" + createGrants = "" + message = "User created." + } else { + message = "Unable to create user." + } + } + }) { Text("Create user") } + message?.let { Text(text = it) } + } + } + + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(text = "Existing users", fontWeight = FontWeight.SemiBold) + users.forEach { user -> + UserCard(api = api, session = session, user = user, onReload = { + scope.launch { users = api.listUsers() } + }) + if (user != users.last()) { + HorizontalDivider() + } + } + } + } + } + } +} + +@Composable +private fun UserCard( + api: ApiClient, + session: SessionInfo, + user: UserRecord, + onReload: () -> Unit, +) { + val scope = rememberCoroutineScope() + var role by rememberSaveable(user.id) { mutableStateOf(user.role) } + var password by rememberSaveable(user.id) { mutableStateOf("") } + var grants by rememberSaveable(user.id) { mutableStateOf(formatPrinterGrants(user.printerGrants)) } + var message by rememberSaveable(user.id) { mutableStateOf(null) } + + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + Column(modifier = Modifier.weight(1f)) { + Text(text = user.username, fontWeight = FontWeight.Medium) + Text(text = user.createdAt ?: "Unknown creation date", style = MaterialTheme.typography.bodySmall) + } + StatusPill(text = user.role, ok = user.role == "admin") + } + OutlinedTextField(value = role, onValueChange = { role = it }, modifier = Modifier.fillMaxWidth(), label = { Text("Role") }) + OutlinedTextField(value = password, onValueChange = { password = it }, modifier = Modifier.fillMaxWidth(), label = { Text("New password") }) + OutlinedTextField(value = grants, onValueChange = { grants = it }, modifier = Modifier.fillMaxWidth(), label = { Text("Printer grants") }, minLines = 3) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Button(onClick = { + scope.launch { + val payload = JSONObject() + .put("role", role) + .put("printer_grants", printerGrantsToJson(grants)) + if (password.isNotBlank()) { + payload.put("password", password) + } + message = if (api.updateUser(user.id, payload, session.csrfToken)) "User updated." else "Unable to update user." + onReload() + } + }) { Text("Save") } + OutlinedButton(onClick = { + scope.launch { + message = if (api.deleteUser(user.id, session.csrfToken)) "User deleted." else "Unable to delete user." + onReload() + } + }) { Text("Delete") } + } + message?.let { Text(text = it) } + } +} + +@Composable +private fun AuditScreen(api: ApiClient) { + var events by remember { mutableStateOf>(emptyList()) } + var loading by rememberSaveable { mutableStateOf(true) } + val scope = rememberCoroutineScope() + + LaunchedEffect(Unit) { + events = api.getAudit() + loading = false + } + + ScreenBody(headline = "Audit log", subheadline = "Recent security and printer events", scrollable = true, refreshing = loading, onRefresh = { + scope.launch { + loading = true + events = api.getAudit() + loading = false + } + }) { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + if (loading) { + LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + } else if (events.isEmpty()) { + Text(text = "No audit events yet.") + } else { + events.forEach { event -> + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + Text(text = event.timestamp ?: "Unknown time", style = MaterialTheme.typography.bodySmall) + StatusPill(text = event.action ?: "event", ok = false) + } + Text(text = listOfNotNull(event.actor, event.printerId, event.targetId, event.method, event.path).joinToString(" โ€ข ")) + event.detail?.let { Text(text = it) } + } + } + } + } + } + } +} + +@Composable +private fun InstallScreen(api: ApiClient, csrfToken: String, printerId: String) { + val scope = rememberCoroutineScope() + var host by rememberSaveable { mutableStateOf("") } + var serverUrl by rememberSaveable { mutableStateOf(api.baseUrlString()) } + var port by rememberSaveable { mutableStateOf("22") } + var username by rememberSaveable { mutableStateOf("") } + var password by rememberSaveable { mutableStateOf("") } + var printer by rememberSaveable { mutableStateOf(printerId) } + var hostType by rememberSaveable { mutableStateOf("standard") } + var hostTypeMenuExpanded by rememberSaveable { mutableStateOf(false) } + var moonrakerUrl by rememberSaveable { mutableStateOf("http://127.0.0.1:7125") } + var uiUrl by rememberSaveable { mutableStateOf("") } + var uiAutoDetect by rememberSaveable { mutableStateOf(true) } + var status by rememberSaveable { mutableStateOf(null) } + var output by rememberSaveable { mutableStateOf(null) } + var job by remember { mutableStateOf(null) } + var polling by rememberSaveable { mutableStateOf(false) } + + LaunchedEffect(printerId) { + if (printerId.isNotBlank()) { + printer = printerId + val detail = api.getPrinter(printerId) + val install = detail?.settings?.install + if (install != null) { + serverUrl = install.serverUrl ?: serverUrl + host = install.host ?: host + port = (install.port?.toString() ?: port) + username = install.username ?: username + moonrakerUrl = install.moonrakerUrl ?: moonrakerUrl + uiUrl = install.uiUrl ?: uiUrl + uiAutoDetect = install.uiAutoDetect ?: uiAutoDetect + hostType = install.hostType ?: hostType + } + } + } + + ScreenBody(headline = "Install printer over SSH", subheadline = "Connect to the printer host, upload the installer, and start the agent without touching the host manually.", scrollable = true) { + Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + OutlinedTextField(value = host, onValueChange = { host = it }, modifier = Modifier.fillMaxWidth(), label = { Text("Printer host / IP") }) + OutlinedTextField(value = serverUrl, onValueChange = { serverUrl = it }, modifier = Modifier.fillMaxWidth(), label = { Text("Server URL") }) + OutlinedTextField(value = port, onValueChange = { port = it.filter { ch -> ch.isDigit() } }, modifier = Modifier.fillMaxWidth(), label = { Text("SSH port") }) + OutlinedTextField(value = username, onValueChange = { username = it }, modifier = Modifier.fillMaxWidth(), label = { Text("SSH username") }) + OutlinedTextField(value = password, onValueChange = { password = it }, modifier = Modifier.fillMaxWidth(), label = { Text("SSH password") }) + OutlinedTextField(value = printer, onValueChange = { printer = it }, modifier = Modifier.fillMaxWidth(), label = { Text("Printer ID") }) + Text(text = "Printer host type", fontWeight = FontWeight.Medium) + Box { + OutlinedButton( + onClick = { hostTypeMenuExpanded = true }, + modifier = Modifier.fillMaxWidth(), + ) { + Text(hostTypeLabel(hostType)) + } + DropdownMenu( + expanded = hostTypeMenuExpanded, + onDismissRequest = { hostTypeMenuExpanded = false }, + ) { + installHostTypes.forEach { option -> + DropdownMenuItem( + text = { Text(option.second) }, + onClick = { + hostType = option.first + hostTypeMenuExpanded = false + }, + ) + } + } + } + Text( + text = "Choose Rinkhals only if the printer host runs the Rinkhals app framework. Standard installs use a service or init script.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + OutlinedTextField(value = moonrakerUrl, onValueChange = { moonrakerUrl = it }, modifier = Modifier.fillMaxWidth(), label = { Text("Moonraker URL") }) + OutlinedTextField(value = uiUrl, onValueChange = { uiUrl = it }, modifier = Modifier.fillMaxWidth(), label = { Text("UI URL") }) + Row(verticalAlignment = Alignment.CenterVertically) { + Switch(checked = uiAutoDetect, onCheckedChange = { uiAutoDetect = it }) + Text(text = "Auto-detect the printer UI on the host") + } + Button(onClick = { + scope.launch { + val payload = JSONObject() + .put("host", host) + .put("server_url", normalizeServerUrl(serverUrl) ?: serverUrl) + .put("port", port.toIntOrNull() ?: 22) + .put("username", username) + .put("password", password) + .put("printer_id", printer) + .put("host_type", hostType) + .put("moonraker_url", moonrakerUrl) + .put("ui_url", uiUrl) + .put("ui_auto_detect", uiAutoDetect) + val started = api.startInstall(payload, csrfToken) + if (started != null) { + val jobId = started.optString("job_id") + if (jobId.isNotBlank()) { + polling = true + status = started.optString("message").ifBlank { "Installer job started." } + output = status + while (true) { + val current = api.pollInstallJob(jobId) + job = current + output = current?.output ?: current?.message + status = current?.message ?: status + if (current == null || (current.status != "queued" && current.status != "running")) { + break + } + delay(1000) + } + polling = false + } else { + status = "Installer job started, but no job id was returned." + } + } else { + status = "Unable to start install job." + } + } + }) { Text("Install agent") } + status?.let { Text(text = it) } + } + } + if (polling || job != null) { + Card { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text(text = "Install result", fontWeight = FontWeight.SemiBold) + job?.let { + FactGrid( + facts = listOf( + "Status" to (it.status ?: "unknown"), + "Stage" to (it.stage ?: "unknown"), + "Printer" to (it.printerId ?: printer), + "Host" to listOfNotNull(it.host, it.port?.toString()).joinToString(":"), + "Host type" to (it.hostType ?: "unknown"), + "Server" to (it.serverUrl ?: serverUrl), + "Remote host" to (it.remoteHost ?: "unknown"), + "Binary" to (it.binarySource ?: "unknown"), + "Config" to (it.configPath ?: "unknown"), + "Post-install" to if (it.postInstallConnected == true) "Confirmed" else "Pending", + "Callback" to (it.postInstallMessage ?: "Waiting"), + "Rollback" to if (it.rollbackPerformed == true) "Performed" else "Not needed", + "Rollback detail" to (it.rollbackMessage ?: "None"), + ), + ) + } + output?.let { Text(text = it) } + } + } + } + } + } +} + +private val installHostTypes = listOf( + "standard" to "Standard Linux service", + "rinkhals" to "Rinkhals app runtime", +) + +private fun hostTypeLabel(hostType: String): String { + return installHostTypes.firstOrNull { it.first == hostType.trim().lowercase() }?.second ?: "Standard Linux service" +} + +@Composable +private fun ScreenFrame( + title: String, + subtitle: String, + topActions: @Composable RowScope.() -> Unit = {}, + content: @Composable () -> Unit, +) { + Scaffold( + topBar = { + Column { + CenterAlignedTopAppBar( + title = { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text(text = title, fontWeight = FontWeight.SemiBold) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + }, + actions = topActions, + ) + HorizontalDivider() + } + }, + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + content() + } + } +} + +@Composable +private fun ScreenBody( + headline: String, + subheadline: String, + scrollable: Boolean = false, + refreshing: Boolean = false, + onRefresh: (() -> Unit)? = null, + trailing: @Composable RowScope.() -> Unit = {}, + content: @Composable () -> Unit, +) { + if (scrollable) { + val scroll = rememberScrollState() + val pullRefreshState = onRefresh?.let { + rememberPullRefreshState( + refreshing = refreshing, + onRefresh = it, + ) + } + ScreenFrame(title = headline, subtitle = subheadline, topActions = trailing) { + Box( + modifier = Modifier + .fillMaxSize() + .then(if (pullRefreshState != null) Modifier.pullRefresh(pullRefreshState) else Modifier), + ) { + Column( + modifier = Modifier.verticalScroll(scroll), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + content() + } + if (pullRefreshState != null) { + PullRefreshIndicator( + refreshing = refreshing, + state = pullRefreshState, + modifier = Modifier.align(Alignment.TopCenter), + ) + } + } + } + } else { + ScreenFrame(title = headline, subtitle = subheadline, topActions = trailing) { + content() + } + } +} + +@Composable +private fun FactGrid(facts: List>) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + facts.forEach { (label, value) -> + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text( + text = label, + modifier = Modifier.weight(0.35f), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = value, + modifier = Modifier.weight(0.65f), + fontWeight = FontWeight.Medium, + ) + } + } + } +} + +private fun Any?.asStringMap(): Map? { + val map = this as? Map<*, *> ?: return null + return map.entries.associate { (key, value) -> key.toString() to value } +} + +private fun Map?.intValue(key: String): Int { + return this?.get(key).asIntOrNull() ?: 0 +} + +private fun Map?.stringValue(key: String): String? { + return this?.get(key)?.toString()?.trim()?.takeIf { it.isNotBlank() } +} + +private data class MmuMaterialFact( + val label: String, + val value: String, + val colorHex: String?, +) + +private fun mmuMaterialFacts(printStatus: PrintStatus?): List { + val status = printStatus?.moonrakerStatus ?: return emptyList() + val mmu = status.get("mmu").asStringMap() ?: return emptyList() + if (!mmu.containsKey("enabled")) { + return emptyList() + } + val label = status.get("mmu_machine") + .asStringMap() + ?.get("unit_0") + .asStringMap() + ?.stringValue("name") + ?: "MMU" + if (!mmu.booleanish("enabled")) { + return listOf(MmuMaterialFact(label = label, value = "Disabled", colorHex = null)) + } + val names = metadataList(mmu["gate_filament_name"]).map { it.toString() } + val materials = metadataList(mmu["gate_material"]).map { it.toString() } + val colors = metadataList(mmu["gate_color"]).map { it.toString() } + val count = maxOf(names.size, materials.size, colors.size, mmu.intValue("num_gates")) + if (count == 0) { + return listOf(MmuMaterialFact(label = label, value = "Enabled", colorHex = null)) + } + return buildList { + repeat(count) { index -> + val parts = mutableListOf() + var colorHex: String? = null + names.getOrNull(index)?.takeIf { it.isNotBlank() && it != "Unknown" }?.let { parts.add(it) } + materials.getOrNull(index)?.takeIf { it.isNotBlank() && it != names.getOrNull(index) }?.let { parts.add("($it)") } + colors.getOrNull(index)?.takeIf { it.isNotBlank() }?.let { colorHex = it.filter { ch -> ch.isLetterOrDigit() } } + add(MmuMaterialFact(label = "Gate ${index + 1}", value = parts.joinToString(" ").ifBlank { "Unknown material" }, colorHex = colorHex)) + } + } +} + +@Composable +private fun MmuMaterialSection(facts: List) { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + facts.forEach { fact -> + MmuMaterialRow(fact = fact) + } + } +} + +@Composable +private fun MmuMaterialRow(fact: MmuMaterialFact) { + val swatchColor = remember(fact.colorHex, fact.value) { parseMmuColor(fact.colorHex) } + ?: MaterialTheme.colorScheme.outlineVariant + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(18.dp) + .clip(MaterialTheme.shapes.small) + .background(swatchColor), + ) + Column(modifier = Modifier.weight(1f)) { + Text(text = fact.label, fontWeight = FontWeight.SemiBold) + Text( + text = fact.value, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +private fun temperatureSummaryText(printStatus: PrintStatus?): String? { + val facts = temperatureFacts(printStatus) + if (facts.isEmpty()) { + return null + } + return facts.joinToString(" ยท ") { "${it.first} ${it.second}" } +} + +private fun temperatureFacts(printStatus: PrintStatus?): List> { + val status = printStatus?.moonrakerStatus ?: return emptyList() + val rows = mutableListOf>() + val seen = mutableSetOf() + + fun add(key: String, label: String) { + val sensor = status[key].asStringMap() ?: return + val reading = formatTemperatureReading(sensor) ?: return + rows.add(label to reading) + seen.add(key) + } + + add("extruder", "Hotend") + add("heater_bed", "Bed") + add("temperature_sensor chamber", "Chamber") + + status.keys.sorted().forEach { key -> + if (seen.contains(key) || !isTemperatureSensorKey(key)) { + return@forEach + } + val sensor = status[key].asStringMap() ?: return@forEach + val reading = formatTemperatureReading(sensor) ?: return@forEach + rows.add(prettifyTemperatureLabel(key) to reading) + } + + return rows +} + +private fun isTemperatureSensorKey(key: String): Boolean { + return key.startsWith("temperature_sensor ") || + key.startsWith("temperature_fan ") || + key.startsWith("temperature_probe ") +} + +private fun prettifyTemperatureLabel(key: String): String { + val raw = key + .replace(Regex("^temperature_(sensor|fan|probe)\\s+", RegexOption.IGNORE_CASE), "") + .replace('_', ' ') + .trim() + if (raw.isBlank()) { + return "Sensor" + } + return raw.split(Regex("\\s+")).joinToString(" ") { part -> + part.replaceFirstChar { ch -> if (ch.isLowerCase()) ch.titlecase(Locale.US) else ch.toString() } + } +} + +private fun formatTemperatureReading(sensor: Map): String? { + val current = sensor["temperature"].asDoubleOrNull() ?: return null + val target = sensor["target"].asDoubleOrNull() + return if (target != null && target > 0) { + String.format(Locale.US, "%.1f / %.1f\u00b0C", current, target) + } else { + String.format(Locale.US, "%.1f\u00b0C", current) + } +} + +private fun parseMmuColor(value: String?): Color? { + val raw = value?.trim()?.replace(Regex("[^0-9a-fA-F]"), "")?.takeIf { it.isNotBlank() } ?: return null + return try { + when (raw.length) { + 8 -> { + val r = raw.substring(0, 2).toInt(16) + val g = raw.substring(2, 4).toInt(16) + val b = raw.substring(4, 6).toInt(16) + val a = raw.substring(6, 8).toInt(16) + Color(android.graphics.Color.argb(a, r, g, b)) + } + 6 -> Color(android.graphics.Color.parseColor("#$raw")) + 3 -> { + val expanded = raw.map { "$it$it" }.joinToString("") + Color(android.graphics.Color.parseColor("#$expanded")) + } + else -> null + } + } catch (_: IllegalArgumentException) { + null + } +} + +private fun metadataList(value: Any?): List { + return when (value) { + null -> emptyList() + is List<*> -> value.filterNotNull() + is Array<*> -> value.filterNotNull().toList() + else -> listOf(value) + } +} + +private fun Any?.asDoubleOrNull(): Double? { + return when (this) { + is Number -> toDouble() + is String -> toDoubleOrNull() + else -> null + } +} + +private fun Any?.asIntOrNull(): Int? { + return when (this) { + is Number -> toInt() + is String -> toIntOrNull() + else -> null + } +} + +private fun Map.booleanish(key: String): Boolean { + val value = this[key] ?: return false + return when (value) { + is Boolean -> value + is Number -> value.toInt() != 0 + is String -> value.equals("true", ignoreCase = true) || value == "1" + else -> false + } +} + +private fun formatMmuWeight(value: Double): String { + return String.format(Locale.US, "%.1f g", value) +} + +@Composable +private fun JobRow(job: RecentJob) { + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + Text(text = job.filename, fontWeight = FontWeight.Medium) + StatusPill(text = job.status, ok = job.status.equals("completed", ignoreCase = true)) + } + FactGrid( + facts = listOf( + "Duration" to formatDuration(job.totalDuration ?: job.printDuration), + "Started" to formatHistoryTime(job.startTime), + "Ended" to formatHistoryTime(job.endTime), + "Message" to (job.message ?: "No message"), + ), + ) + } +} + +@Composable +private fun StatusPill(text: String, ok: Boolean) { + val background = if (ok) Color(0xFF1C5C4E) else Color(0xFF5C3A1C) + Text( + text = text, + color = Color.White, + modifier = Modifier + .clip(MaterialTheme.shapes.small) + .background(background) + .padding(horizontal = 10.dp, vertical = 4.dp), + style = MaterialTheme.typography.labelMedium, + ) +} + +private fun printerGrantsToJson(raw: String): org.json.JSONArray { + val grants = org.json.JSONArray() + raw.lineSequence().forEach { line -> + val trimmed = line.trim() + if (trimmed.isBlank()) { + return@forEach + } + val parts = trimmed.split(":") + if (parts.size != 2) { + return@forEach + } + val printerId = parts[0].trim() + val access = parts[1].trim().lowercase() + if (printerId.isBlank() || (access != "read" && access != "control")) { + return@forEach + } + grants.put(JSONObject().put("printer_id", printerId).put("access", access)) + } + return grants +} + +private fun formatPrinterGrants(grants: List): String { + if (grants.isEmpty()) { + return "" + } + return grants.joinToString("\n") { "${it.printerId}:${it.access}" } +} + +private fun syncPrinterUiCookies( + api: ApiClient, + printerId: String, + webView: WebView, + onComplete: () -> Unit, +) { + val cookieManager = WebCookieManager.getInstance() + cookieManager.setAcceptCookie(true) + cookieManager.setAcceptThirdPartyCookies(webView, true) + val origin = "${api.baseUrlString().trimEnd('/')}/" + val cookies = buildList { + add("ka_printer_context=$printerId; Path=/") + api.webViewCookies().forEach { cookie -> + if (cookie.name.isBlank()) { + return@forEach + } + val path = cookie.path?.takeIf { it.isNotBlank() } ?: "/" + val parts = buildList { + add("${cookie.name}=${cookie.value}") + add("Path=$path") + cookie.domain?.takeIf { it.isNotBlank() }?.let { add("Domain=$it") } + if (cookie.secure) { + add("Secure") + } + } + add(parts.joinToString("; ")) + } + } + if (cookies.isEmpty()) { + onComplete() + return + } + var remaining = cookies.size + cookies.forEach { cookie -> + cookieManager.setCookie(origin, cookie) { + remaining -= 1 + if (remaining <= 0) { + cookieManager.flush() + onComplete() + } + } + } +} + +private fun openExternal(context: Context, url: String) { + val target = url.trim() + if (target.isBlank()) { + Toast.makeText(context, "No URL available to open.", Toast.LENGTH_SHORT).show() + return + } + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(target)).apply { + addCategory(Intent.CATEGORY_BROWSABLE) + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + try { + context.startActivity(Intent.createChooser(intent, "Open printer UI").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } catch (_: ActivityNotFoundException) { + Toast.makeText(context, "No browser app found to open this link.", Toast.LENGTH_SHORT).show() + } +} + +private fun printerUiTargetUrl(api: ApiClient, printerId: String): String { + return api.printerUiUrl(printerId) +} + +private fun printerUiModePrefKey(serverUrl: String, printerId: String): String { + return "$PREF_PRINTER_UI_MODE_PREFIX:${serverUrl.trim()}:${printerId.trim()}" +} + +private fun resolvePrinterUiLaunchMode(context: Context, serverUrl: String, printerId: String): PrinterUiLaunchMode { + return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .getString(printerUiModePrefKey(serverUrl, printerId), PrinterUiLaunchMode.Embedded.name) + ?.let { raw -> + enumValues().firstOrNull { it.name == raw } ?: PrinterUiLaunchMode.Embedded + } + ?: PrinterUiLaunchMode.Embedded +} + +private fun savePrinterUiLaunchMode(context: Context, serverUrl: String, printerId: String, mode: PrinterUiLaunchMode) { + context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .edit() + .putString(printerUiModePrefKey(serverUrl, printerId), mode.name) + .apply() +} + +private fun printerUiLaunchModeLabel(mode: PrinterUiLaunchMode): String { + return when (mode) { + PrinterUiLaunchMode.Embedded -> "In-app WebView" + PrinterUiLaunchMode.External -> "External browser" + } +} + +private fun loadSavedServerUrl(context: Context): String { + return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .getString(PREF_SERVER_URL, "") + .orEmpty() +} + +private fun saveServerUrl(context: Context, url: String) { + context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .edit() + .putString(PREF_SERVER_URL, url) + .apply() +} + +private fun formatRelativeTime(unixSeconds: Long?): String { + if (unixSeconds == null || unixSeconds <= 0) { + return "Unknown" + } + val seconds = (System.currentTimeMillis() / 1000L) - unixSeconds + return when { + seconds < 5 -> "just now" + seconds < 60 -> "${seconds}s ago" + seconds < 3600 -> "${seconds / 60}m ago" + else -> "${seconds / 3600}h ago" + } +} + +private fun formatDuration(value: Double?): String { + if (value == null || value < 0) { + return "Unknown" + } + val whole = value.toLong() + val hours = whole / 3600 + val minutes = (whole % 3600) / 60 + val seconds = whole % 60 + return when { + hours > 0 -> "${hours}h ${minutes}m ${seconds}s" + minutes > 0 -> "${minutes}m ${seconds}s" + else -> "${seconds}s" + } +} + +private fun formatHistoryTime(unixSeconds: Long?): String { + if (unixSeconds == null || unixSeconds <= 0) { + return "Unknown" + } + return java.text.SimpleDateFormat.getDateTimeInstance().format(java.util.Date(unixSeconds * 1000L)) +} + +private fun formatPercent(value: Double?): String { + if (value == null) { + return "0%" + } + return if (value <= 1.0) "${(value * 100).toInt()}%" else "${value.toInt()}%" +} + +private fun formatFilament(value: Double?): String { + if (value == null || value <= 0) { + return "Unknown" + } + return "${"%.1f".format(value)} mm" +} + +@Composable +private fun KlipperAnywhereTheme(content: @Composable () -> Unit) { + val darkColors = androidx.compose.material3.darkColorScheme( + primary = Color(0xFF8ED7D0), + onPrimary = Color(0xFF09231F), + secondary = Color(0xFFFFB36B), + onSecondary = Color(0xFF2F1600), + tertiary = Color(0xFF89A7FF), + onTertiary = Color(0xFF0A1633), + background = Color(0xFF081018), + onBackground = Color(0xFFE7EEF5), + surface = Color(0xFF111A24), + onSurface = Color(0xFFE7EEF5), + surfaceVariant = Color(0xFF223243), + onSurfaceVariant = Color(0xFFAFC1D1), + error = Color(0xFFFFB4AB), + onError = Color(0xFF690005), + errorContainer = Color(0xFF93000A), + onErrorContainer = Color(0xFFFFDAD6), + ) + androidx.compose.material3.MaterialTheme( + colorScheme = darkColors, + typography = androidx.compose.material3.MaterialTheme.typography, + content = content, + ) +} + + diff --git a/android/app/src/main/java/com/klipperanywhere/android/Models.kt b/android/app/src/main/java/com/klipperanywhere/android/Models.kt new file mode 100644 index 0000000..dfdad7d --- /dev/null +++ b/android/app/src/main/java/com/klipperanywhere/android/Models.kt @@ -0,0 +1,190 @@ +package com.klipperanywhere.android + +data class SessionInfo( + val authenticated: Boolean, + val userId: String, + val username: String, + val role: String, + val isAdmin: Boolean, + val printerGrants: List, + val csrfToken: String, + val serverVersion: String, +) + +data class PrinterGrant( + val printerId: String, + val access: String, +) + +data class CameraInfo( + val name: String, + val hasSnapshot: Boolean, + val hasStream: Boolean, + val aspectRatio: String?, + val rotation: Int?, + val flipHorizontal: Boolean, + val flipVertical: Boolean, + val location: String?, + val service: String?, + val source: String?, +) + +data class PrinterHealth( + val connected: Boolean, + val moonrakerReachable: Boolean, + val moonrakerState: String?, + val moonrakerMessage: String?, + val checkedAtUnix: Long?, + val uiReachable: Boolean, + val uiSource: String?, + val uiUrl: String?, + val uiAutoDetect: Boolean, + val controlMode: String?, + val agentVersion: String?, + val hostname: String?, + val cameras: List, + val printStatus: PrintStatus?, +) + +data class PrinterInfo( + val hostname: String?, + val softwareVersion: String?, + val cpuInfo: String?, + val configFile: String?, + val logFile: String?, +) + +data class PrintStatus( + val state: String?, + val filename: String?, + val progress: Double?, + val printDuration: Double?, + val totalDuration: Double?, + val estimatedRemaining: Double?, + val filamentUsed: Double?, + val message: String?, + val moonrakerStatus: Map?, + val moonrakerMetadata: Map?, + val moonrakerMetadataFilename: String?, + val layerSource: String?, +) + +data class RecentJob( + val filename: String, + val status: String, + val totalDuration: Double?, + val printDuration: Double?, + val startTime: Long?, + val endTime: Long?, + val message: String?, +) + +data class InstallSummary( + val hostType: String?, + val serverUrl: String?, + val host: String?, + val port: Int?, + val username: String?, + val moonrakerUrl: String?, + val uiUrl: String?, + val uiAutoDetect: Boolean?, + val status: String?, + val message: String?, + val error: String?, + val binarySource: String?, + val configPath: String?, + val postInstallConnected: Boolean?, + val postInstallMessage: String?, + val rollbackPerformed: Boolean?, + val rollbackMessage: String?, +) + +data class PrinterSettingsView( + val displayName: String?, + val controlMode: String?, + val uiUrl: String?, + val uiAutoDetect: Boolean, + val notificationSnapshotCamera: String?, + val updatedAt: String?, + val lastSyncedAt: String?, + val install: InstallSummary?, + val printNotificationsEnabled: Boolean, + val notifyPrintStarted: Boolean, + val notifyPrintPaused: Boolean, + val notifyPrintResumed: Boolean, + val notifyPrintCompleted: Boolean, + val notifyPrintCanceled: Boolean, + val notifyPrintFailed: Boolean, + val notifyFirstLayer: Boolean, + val notifyThirdLayer: Boolean, +) + +data class PrinterSummary( + val printerId: String, + val connected: Boolean, + val health: PrinterHealth?, + val settings: PrinterSettingsView, +) + +data class PrinterDetail( + val printerId: String, + val connected: Boolean, + val health: PrinterHealth?, + val info: PrinterInfo?, + val printStatus: PrintStatus?, + val recentJobs: List, + val controlMode: String?, + val access: String?, + val settings: PrinterSettingsView, + val settingsSynced: Boolean, + val settingsSyncState: String?, + val settingsSyncDetail: String?, +) + +data class UserRecord( + val id: String, + val username: String, + val role: String, + val createdAt: String?, + val printerGrants: List, +) + +data class AdminNotificationSettings( + val telegramEnabled: Boolean, + val telegramCommandsEnabled: Boolean, + val telegramBotTokenSet: Boolean, + val telegramBotToken: String?, + val telegramChatId: String?, +) + +data class AuditEvent( + val timestamp: String?, + val actor: String?, + val action: String?, + val printerId: String?, + val targetId: String?, + val method: String?, + val path: String?, + val detail: String?, + val status: Any?, +) + +data class InstallJob( + val id: String, + val status: String?, + val stage: String?, + val message: String?, + val output: String?, + val printerId: String?, + val host: String?, + val port: Int?, + val hostType: String?, + val serverUrl: String?, + val remoteHost: String?, + val binarySource: String?, + val configPath: String?, + val postInstallConnected: Boolean?, + val postInstallMessage: String?, + val rollbackPerformed: Boolean?, + val rollbackMessage: String?, +) diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.png b/android/app/src/main/res/drawable/ic_launcher_foreground.png new file mode 100644 index 0000000..dcb7574 Binary files /dev/null and b/android/app/src/main/res/drawable/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..44cebc6 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..44cebc6 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..babd05a Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..babd05a Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..932b9cb Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..932b9cb Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..263cec3 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..263cec3 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..393ccad Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..393ccad Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..946d844 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..946d844 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f543338 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + #8ED7D0 + #FFB36B + #081018 + #111A24 + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..224e7fb --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + KlipperAnywhere + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..b92855e --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,8 @@ + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..017d909 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.application") version "8.5.2" apply false + id("org.jetbrains.kotlin.android") version "1.9.24" apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..95b6d58 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,4 @@ +android.useAndroidX=true +android.nonTransitiveRClass=true +kotlin.code.style=official +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 diff --git a/android/gradle/wrapper/gradle-wrapper-shared.jar b/android/gradle/wrapper/gradle-wrapper-shared.jar new file mode 100644 index 0000000..651d485 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper-shared.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..c8ea8b2 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b82aa23 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100644 index 0000000..1813c99 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,23 @@ +#!/usr/bin/env sh + +set -eu + +APP_HOME="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +GRADLE_HOME="" + +for d in "$HOME/.gradle/wrapper/dists/gradle-8.7-bin"/*/gradle-8.7; do + if [ -d "$d" ]; then + GRADLE_HOME="$d" + fi +done + +if [ -z "$GRADLE_HOME" ]; then + echo "Unable to locate the cached Gradle 8.7 distribution." >&2 + exit 1 +fi + +if [ -z "${JAVA_HOME:-}" ] && [ -x "/c/Program Files/Android/Android Studio/jbr/bin/java.exe" ]; then + export JAVA_HOME="/c/Program Files/Android/Android Studio/jbr" +fi + +exec "$GRADLE_HOME/bin/gradle" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..591ff73 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,21 @@ +@echo off +setlocal + +set "APP_HOME=%~dp0" +set "GRADLE_HOME=" + +for /d %%D in ("%USERPROFILE%\.gradle\wrapper\dists\gradle-8.7-bin\*") do ( + if exist "%%~fD\gradle-8.7\bin\gradle.bat" set "GRADLE_HOME=%%~fD\gradle-8.7" +) + +if not defined GRADLE_HOME ( + echo Unable to locate the cached Gradle 8.7 distribution. + exit /b 1 +) + +if not defined JAVA_HOME ( + if exist "C:\Program Files\Android\Android Studio\jbr\bin\java.exe" set "JAVA_HOME=C:\Program Files\Android\Android Studio\jbr" +) + +"%GRADLE_HOME%\bin\gradle.bat" %* +exit /b %ERRORLEVEL% diff --git a/android/gradlew.ps1 b/android/gradlew.ps1 new file mode 100644 index 0000000..0d539b8 --- /dev/null +++ b/android/gradlew.ps1 @@ -0,0 +1,8 @@ +param( + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$Arguments +) + +$batch = Join-Path $PSScriptRoot 'gradlew.bat' +& cmd /c "`"$batch`" $($Arguments -join ' ')" +exit $LASTEXITCODE diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..f8cdee9 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "KlipperAnywhereAndroid" +include(":app") diff --git a/cmd/agent/main.go b/cmd/agent/main.go new file mode 100644 index 0000000..5399659 --- /dev/null +++ b/cmd/agent/main.go @@ -0,0 +1,2351 @@ +package main + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "log" + "net/http" + "net/url" + "os" + "os/exec" + "os/signal" + "path/filepath" + "runtime" + "sort" + "strings" + "sync" + "syscall" + "time" + + "github.com/gorilla/websocket" + "github.com/klipperanywhere/klipperanywhere/internal/protocol" +) + +var agentVersion = "dev" + +const ( + normalHeartbeatInterval = 15 * time.Second + activePrintHeartbeatInterval = 2 * time.Second + moonrakerSubscriptionStartupTimeout = 5 * time.Second +) + +const defaultStateFile = "/var/lib/klipperanywhere/agent-state.json" + +type config struct { + ServerURL string `json:"server_url"` + PrinterID string `json:"printer_id"` + Token string `json:"token"` + MoonrakerURL string `json:"moonraker_url"` + ControlMode string `json:"control_mode"` + UIURL string `json:"ui_url"` + UIAutoDetect *bool `json:"ui_auto_detect"` + StateFile string `json:"state_file"` + Cameras []cameraConfig `json:"cameras"` +} + +type cameraConfig struct { + Name string `json:"name"` + SnapshotURL string `json:"snapshot_url"` + StreamURL string `json:"stream_url"` + Source string `json:"source"` + Service string `json:"service"` + Location string `json:"location"` + AspectRatio string `json:"aspect_ratio"` + Rotation int `json:"rotation"` + FlipHorizontal bool `json:"flip_horizontal"` + FlipVertical bool `json:"flip_vertical"` +} + +type cameraStore struct { + mu sync.RWMutex + cameras []cameraConfig +} + +type uiTarget struct { + URL *url.URL + Source string + Reachable bool +} + +type runtimeState struct { + mu sync.RWMutex + uiURL string + uiAutoDetect bool + controlMode string + ui *uiTarget +} + +type moonrakerStatusCache struct { + mu sync.Mutex + status map[string]any + key string + updatedAt time.Time + lastLogAt time.Time +} + +type wsStore struct { + mu sync.Mutex + conns map[string]*websocket.Conn +} + +type agentStatusRecord struct { + PrinterID string `json:"printer_id"` + ServerURL string `json:"server_url"` + MoonrakerURL string `json:"moonraker_url"` + AgentVersion string `json:"agent_version,omitempty"` + ControlMode string `json:"control_mode"` + UIURL string `json:"ui_url,omitempty"` + UIAutoDetect bool `json:"ui_auto_detect"` + UIReachable bool `json:"ui_reachable"` + UISource string `json:"ui_source,omitempty"` + MoonrakerReachable bool `json:"moonraker_reachable"` + MoonrakerState string `json:"moonraker_state,omitempty"` + MoonrakerMessage string `json:"moonraker_message,omitempty"` + PrintStatus *protocol.PrintStatus `json:"print_status,omitempty"` + LastHeartbeatAt time.Time `json:"last_heartbeat_at"` + LastSyncAt time.Time `json:"last_sync_at,omitempty"` + LastSyncDetail string `json:"last_sync_detail,omitempty"` + Cameras []cameraConfig `json:"cameras,omitempty"` +} + +type agentStatusStore struct { + path string + mu sync.Mutex +} + +func newAgentStatusStore(path string) *agentStatusStore { + if path == "" { + path = defaultStateFile + } + return &agentStatusStore{path: path} +} + +func (s *agentStatusStore) recordHeartbeat(record agentStatusRecord) error { + s.mu.Lock() + defer s.mu.Unlock() + current, err := s.readLocked() + if err == nil { + record.LastSyncAt = current.LastSyncAt + record.LastSyncDetail = current.LastSyncDetail + } + return s.writeLocked(record) +} + +func (s *agentStatusStore) recordSync(record agentStatusRecord) error { + s.mu.Lock() + defer s.mu.Unlock() + current, err := s.readLocked() + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + if current.PrinterID != "" { + record.LastHeartbeatAt = current.LastHeartbeatAt + record.Cameras = current.Cameras + record.MoonrakerReachable = current.MoonrakerReachable + record.MoonrakerState = current.MoonrakerState + record.MoonrakerMessage = current.MoonrakerMessage + record.PrintStatus = current.PrintStatus + record.UIReachable = current.UIReachable + record.UISource = current.UISource + if record.PrinterID == "" { + record.PrinterID = current.PrinterID + } + if record.ServerURL == "" { + record.ServerURL = current.ServerURL + } + if record.MoonrakerURL == "" { + record.MoonrakerURL = current.MoonrakerURL + } + } + return s.writeLocked(record) +} + +func (s *agentStatusStore) read() (agentStatusRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.readLocked() +} + +func (s *agentStatusStore) writeLocked(record agentStatusRecord) error { + if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil { + return err + } + encoded, err := json.MarshalIndent(record, "", " ") + if err != nil { + return err + } + encoded = append(encoded, '\n') + return os.WriteFile(s.path, encoded, 0o600) +} + +func (s *agentStatusStore) readLocked() (agentStatusRecord, error) { + data, err := os.ReadFile(s.path) + if err != nil { + return agentStatusRecord{}, err + } + var record agentStatusRecord + if err := json.Unmarshal(data, &record); err != nil { + return agentStatusRecord{}, err + } + return record, nil +} + +func main() { + cfg := config{ + ServerURL: "ws://127.0.0.1:8080/agent/tunnel", + PrinterID: "test", + Token: "dev-token", + MoonrakerURL: "http://127.0.0.1:7125", + ControlMode: "readonly", + StateFile: defaultStateFile, + } + args := os.Args[1:] + if len(args) > 0 && !strings.HasPrefix(args[0], "-") { + switch args[0] { + case "version": + fmt.Println(agentVersion) + return + case "status": + if err := runStatus(args[1:], cfg); err != nil { + log.Fatal(err) + } + return + case "rollback-watchdog": + if err := runRollbackWatchdog(args[1:]); err != nil { + log.Fatal(err) + } + return + case "run": + args = args[1:] + } + } + + runCfg, err := parseRunConfig(args, cfg) + if err != nil { + log.Fatal(err) + } + baseURL, err := url.Parse(runCfg.MoonrakerURL) + if err != nil { + log.Fatalf("invalid moonraker URL: %v", err) + } + tunnelURL, err := withAuthQuery(runCfg.ServerURL, runCfg.PrinterID, runCfg.Token) + if err != nil { + log.Fatalf("invalid server URL: %v", err) + } + stop := make(chan os.Signal, 1) + signal.Notify(stop, os.Interrupt, syscall.SIGTERM) + backoff := 3 * time.Second + for { + err := run(tunnelURL, baseURL, runCfg.UIURL, *runCfg.UIAutoDetect, runCfg.ControlMode, runCfg.Cameras, runCfg.StateFile, runCfg.PrinterID, runCfg.ServerURL, stop) + if err == nil { + return + } + + log.Printf("tunnel stopped: %v; reconnecting in %s", err, backoff) + select { + case <-time.After(backoff): + case <-stop: + return + } + if backoff < 30*time.Second { + backoff *= 2 + if backoff > 30*time.Second { + backoff = 30 * time.Second + } + } + } +} + +func parseRunConfig(args []string, defaults config) (config, error) { + fs := flag.NewFlagSet("klipperanywhere-agent", flag.ContinueOnError) + var configPath string + var serverURLOverride string + var printerIDOverride string + var tokenOverride string + var moonrakerURLOverride string + var stateFileOverride string + + fs.StringVar(&configPath, "config", "", "path to agent JSON config file") + fs.StringVar(&serverURLOverride, "server", "", "server tunnel URL") + fs.StringVar(&printerIDOverride, "printer-id", "", "printer id registered on the server") + fs.StringVar(&tokenOverride, "token", "", "agent token") + fs.StringVar(&moonrakerURLOverride, "moonraker", "", "local Moonraker base URL") + fs.StringVar(&stateFileOverride, "state-file", "", "path to the local agent state file") + if err := fs.Parse(args); err != nil { + return config{}, err + } + + cfg := defaults + if configPath != "" { + fileCfg, err := loadConfig(configPath) + if err != nil { + return config{}, fmt.Errorf("failed to load config: %w", err) + } + cfg = mergeConfig(cfg, fileCfg) + } + if serverURLOverride != "" { + cfg.ServerURL = serverURLOverride + } + if printerIDOverride != "" { + cfg.PrinterID = printerIDOverride + } + if tokenOverride != "" { + cfg.Token = tokenOverride + } + if moonrakerURLOverride != "" { + cfg.MoonrakerURL = moonrakerURLOverride + } + if stateFileOverride != "" { + cfg.StateFile = stateFileOverride + } + if cfg.UIAutoDetect == nil { + enabled := true + cfg.UIAutoDetect = &enabled + } + if cfg.ControlMode == "" { + cfg.ControlMode = "readonly" + } + if cfg.StateFile == "" { + cfg.StateFile = defaultStateFile + } + if err := validateConfig(cfg); err != nil { + return config{}, err + } + return cfg, nil +} + +func runStatus(args []string, defaults config) error { + fs := flag.NewFlagSet("klipperanywhere-agent status", flag.ContinueOnError) + var configPath string + var stateFileOverride string + var jsonOutput bool + fs.StringVar(&configPath, "config", "", "path to agent JSON config file") + fs.StringVar(&stateFileOverride, "state-file", "", "path to the local agent state file") + fs.BoolVar(&jsonOutput, "json", false, "print JSON") + if err := fs.Parse(args); err != nil { + return err + } + cfg, err := parseRunConfig(fs.Args(), defaults) + if err != nil { + return err + } + if configPath != "" { + cfgFromFile, err := loadConfig(configPath) + if err != nil { + return fmt.Errorf("failed to load config: %w", err) + } + cfg = mergeConfig(cfg, cfgFromFile) + } + if stateFileOverride != "" { + cfg.StateFile = stateFileOverride + } + if cfg.StateFile == "" { + cfg.StateFile = defaultStateFile + } + status, err := readAgentStatus(cfg.StateFile) + if err != nil { + return err + } + if jsonOutput { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(status) + } + printAgentStatus(os.Stdout, cfg, status) + return nil +} + +func loadConfig(path string) (config, error) { + f, err := os.Open(path) + if err != nil { + return config{}, err + } + defer f.Close() + + var cfg config + if err := json.NewDecoder(f).Decode(&cfg); err != nil { + return config{}, err + } + return cfg, nil +} + +func mergeConfig(base config, override config) config { + if override.ServerURL != "" { + base.ServerURL = override.ServerURL + } + if override.PrinterID != "" { + base.PrinterID = override.PrinterID + } + if override.Token != "" { + base.Token = override.Token + } + if override.MoonrakerURL != "" { + base.MoonrakerURL = override.MoonrakerURL + } + if override.ControlMode != "" { + base.ControlMode = override.ControlMode + } + if override.UIURL != "" { + base.UIURL = override.UIURL + } + if override.UIAutoDetect != nil { + base.UIAutoDetect = override.UIAutoDetect + } + if override.StateFile != "" { + base.StateFile = override.StateFile + } + if len(override.Cameras) > 0 { + base.Cameras = override.Cameras + } + return base +} + +func validateConfig(cfg config) error { + if cfg.ServerURL == "" { + return errors.New("server_url is required") + } + if cfg.PrinterID == "" { + return errors.New("printer_id is required") + } + if cfg.Token == "" { + return errors.New("token is required") + } + if cfg.MoonrakerURL == "" { + return errors.New("moonraker_url is required") + } + if cfg.ControlMode != "readonly" && cfg.ControlMode != "full" { + return fmt.Errorf("invalid control_mode %q", cfg.ControlMode) + } + return nil +} + +func readAgentStatus(path string) (agentStatusRecord, error) { + store := newAgentStatusStore(path) + return store.read() +} + +func printAgentStatus(w io.Writer, cfg config, status agentStatusRecord) { + lastHeartbeat := "never" + if !status.LastHeartbeatAt.IsZero() { + lastHeartbeat = status.LastHeartbeatAt.Format(time.RFC3339) + } + lastSync := "never" + if !status.LastSyncAt.IsZero() { + lastSync = status.LastSyncAt.Format(time.RFC3339) + } + fmt.Fprintf(w, "KlipperAnywhere Agent\n") + fmt.Fprintf(w, " printer: %s\n", firstNonEmpty(status.PrinterID, cfg.PrinterID)) + fmt.Fprintf(w, " server: %s\n", firstNonEmpty(status.ServerURL, cfg.ServerURL)) + fmt.Fprintf(w, " moonraker: %s\n", firstNonEmpty(status.MoonrakerURL, cfg.MoonrakerURL)) + fmt.Fprintf(w, " version: %s\n", firstNonEmpty(status.AgentVersion, agentVersion)) + fmt.Fprintf(w, " control mode: %s\n", firstNonEmpty(status.ControlMode, cfg.ControlMode)) + fmt.Fprintf(w, " ui: %s\n", firstNonEmpty(status.UIURL, cfg.UIURL)) + fmt.Fprintf(w, " ui auto-detect: %t\n", status.UIAutoDetect) + fmt.Fprintf(w, " ui source: %s\n", firstNonEmpty(status.UISource, "unknown")) + fmt.Fprintf(w, " ui reachable: %t\n", status.UIReachable) + fmt.Fprintf(w, " moonraker reachable: %t\n", status.MoonrakerReachable) + fmt.Fprintf(w, " moonraker state: %s\n", firstNonEmpty(status.MoonrakerState, "unknown")) + fmt.Fprintf(w, " last heartbeat: %s\n", lastHeartbeat) + fmt.Fprintf(w, " last sync: %s\n", lastSync) + if status.LastSyncDetail != "" { + fmt.Fprintf(w, " sync detail: %s\n", status.LastSyncDetail) + } +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return value + } + } + return "" +} + +func run(tunnelURL string, moonrakerURL *url.URL, configuredUIURL string, uiAutoDetect bool, controlMode string, cameras []cameraConfig, stateFile string, printerID string, serverURL string, stop <-chan os.Signal) error { + conn, _, err := websocket.DefaultDialer.Dial(tunnelURL, nil) + if err != nil { + return err + } + defer conn.Close() + + log.Printf("connected to %s", tunnelURL) + + var writeMu sync.Mutex + errCh := make(chan error, 1) + store := &cameraStore{cameras: discoverCameras(moonrakerURL, cameras)} + wsStore := &wsStore{conns: make(map[string]*websocket.Conn)} + statusStore := newAgentStatusStore(stateFile) + statusCache := &moonrakerStatusCache{} + state := &runtimeState{uiURL: configuredUIURL, uiAutoDetect: uiAutoDetect, controlMode: controlMode} + state.ui = discoverUI(configuredUIURL, uiAutoDetect, moonrakerURL) + done := make(chan struct{}) + subscriptionReady := make(chan struct{}) + defer close(done) + go heartbeatLoop(done, subscriptionReady, errCh, conn, &writeMu, moonrakerURL, state, cameras, store, statusStore, statusCache, printerID, serverURL) + go moonrakerSubscriptionLoop(done, subscriptionReady, conn, &writeMu, moonrakerURL, state, store, statusStore, statusCache, printerID, serverURL) + go func() { + for { + var msg protocol.Message + if err := conn.ReadJSON(&msg); err != nil { + errCh <- err + return + } + if msg.Target == "ws_frame" { + wsStore.write(msg) + continue + } + if msg.Type == protocol.MessageConfigSync { + if err := applyConfigSync(state, moonrakerURL, &writeMu, conn, store.snapshot(), statusStore, statusCache, printerID, serverURL, msg); err != nil { + log.Printf("failed to apply config sync: %v", err) + } + continue + } + if msg.Type != protocol.MessageHTTPRequest { + continue + } + go handleRequest(conn, &writeMu, wsStore, moonrakerURL, state.snapshotUI(), store.snapshot(), stateFile, msg) + } + }() + + select { + case err := <-errCh: + return err + case <-stop: + return nil + } +} + +func heartbeatLoop(done <-chan struct{}, subscriptionReady <-chan struct{}, errCh chan<- error, conn *websocket.Conn, writeMu *sync.Mutex, moonrakerURL *url.URL, state *runtimeState, configured []cameraConfig, store *cameraStore, statusStore *agentStatusStore, cache *moonrakerStatusCache, printerID string, serverURL string) { + waitForMoonrakerSubscription(subscriptionReady) + lastFullRefresh := time.Now() + printStatus, err := sendHeartbeat(conn, writeMu, moonrakerURL, state.snapshotUI(), state.snapshotControlMode(), state.snapshotUIAutoDetect(), store.snapshot(), statusStore, cache, printerID, serverURL) + if err != nil { + reportAgentLoopError(errCh, fmt.Errorf("heartbeat write failed: %w", err)) + return + } + for { + interval := normalHeartbeatInterval + if isActivePrintStatus(printStatus) { + interval = activePrintHeartbeatInterval + } + select { + case <-time.After(interval): + case <-done: + return + } + + if time.Since(lastFullRefresh) >= normalHeartbeatInterval { + store.replace(discoverCameras(moonrakerURL, configured)) + state.refreshUI(moonrakerURL) + lastFullRefresh = time.Now() + } + printStatus, err = sendHeartbeat(conn, writeMu, moonrakerURL, state.snapshotUI(), state.snapshotControlMode(), state.snapshotUIAutoDetect(), store.snapshot(), statusStore, cache, printerID, serverURL) + if err != nil { + reportAgentLoopError(errCh, fmt.Errorf("heartbeat write failed: %w", err)) + return + } + } +} + +func reportAgentLoopError(errCh chan<- error, err error) { + select { + case errCh <- err: + default: + } +} + +func (s *runtimeState) snapshot() (string, bool, string) { + s.mu.RLock() + defer s.mu.RUnlock() + return s.uiURL, s.uiAutoDetect, s.controlMode +} + +func (s *runtimeState) snapshotUI() *uiTarget { + s.mu.RLock() + defer s.mu.RUnlock() + if s.ui == nil { + return nil + } + copy := *s.ui + return © +} + +func (s *runtimeState) snapshotUIURL() string { + s.mu.RLock() + defer s.mu.RUnlock() + return s.uiURL +} + +func (s *runtimeState) snapshotControlMode() string { + s.mu.RLock() + defer s.mu.RUnlock() + return s.controlMode +} + +func (s *runtimeState) snapshotUIAutoDetect() bool { + s.mu.RLock() + defer s.mu.RUnlock() + return s.uiAutoDetect +} + +func (s *runtimeState) apply(settings protocol.Settings) { + s.mu.Lock() + s.uiURL = settings.UIURL + s.uiAutoDetect = settings.UIAutoDetect + if settings.ControlMode != "" { + s.controlMode = settings.ControlMode + } + s.mu.Unlock() +} + +func (s *runtimeState) refreshUI(moonrakerURL *url.URL) { + uiURL, uiAutoDetect, _ := s.snapshot() + ui := discoverUI(uiURL, uiAutoDetect, moonrakerURL) + s.mu.Lock() + s.ui = ui + s.mu.Unlock() +} + +func applyConfigSync(state *runtimeState, moonrakerURL *url.URL, writeMu *sync.Mutex, conn *websocket.Conn, cameras []cameraConfig, statusStore *agentStatusStore, cache *moonrakerStatusCache, printerID string, serverURL string, msg protocol.Message) error { + if msg.Settings == nil { + return writeJSONLocked(conn, writeMu, protocol.Message{ + ID: msg.ID, + Type: protocol.MessageHTTPResponse, + Status: http.StatusOK, + }) + } + state.apply(*msg.Settings) + state.refreshUI(moonrakerURL) + if _, err := sendHeartbeat(conn, writeMu, moonrakerURL, state.snapshotUI(), state.snapshotControlMode(), state.snapshotUIAutoDetect(), cameras, statusStore, cache, printerID, serverURL); err != nil { + return err + } + if statusStore != nil { + if err := statusStore.recordSync(agentStatusRecord{ + PrinterID: printerID, + ServerURL: serverURL, + MoonrakerURL: moonrakerURL.String(), + AgentVersion: agentVersion, + ControlMode: state.snapshotControlMode(), + UIURL: state.snapshotUIURL(), + UIAutoDetect: state.snapshotUIAutoDetect(), + LastSyncAt: time.Now().UTC(), + LastSyncDetail: "accepted server config sync", + }); err != nil { + log.Printf("failed to record agent sync state: %v", err) + } + } + log.Printf("applied config sync control_mode=%s ui_url=%q ui_auto_detect=%t", state.snapshotControlMode(), state.snapshotUIURL(), state.snapshotUIAutoDetect()) + return writeJSONLocked(conn, writeMu, protocol.Message{ + ID: msg.ID, + Type: protocol.MessageHTTPResponse, + Status: http.StatusOK, + }) +} + +func (s *cameraStore) snapshot() []cameraConfig { + s.mu.RLock() + defer s.mu.RUnlock() + cameras := make([]cameraConfig, len(s.cameras)) + copy(cameras, s.cameras) + return cameras +} + +func (s *cameraStore) replace(cameras []cameraConfig) { + s.mu.Lock() + s.cameras = cameras + s.mu.Unlock() +} + +func sendHeartbeat(conn *websocket.Conn, writeMu *sync.Mutex, moonrakerURL *url.URL, ui *uiTarget, controlMode string, uiAutoDetect bool, cameras []cameraConfig, statusStore *agentStatusStore, cache *moonrakerStatusCache, printerID string, serverURL string) (*protocol.PrintStatus, error) { + printStatus := cachedMoonrakerPrintStatus(cache, moonrakerURL) + if printStatus == nil { + printStatus = collectPrintStatus(moonrakerURL) + if cache != nil && printStatus != nil { + cache.seed(printStatus) + } + } + return printStatus, sendHeartbeatWithPrintStatus(conn, writeMu, moonrakerURL, ui, controlMode, uiAutoDetect, cameras, statusStore, printerID, serverURL, printStatus) +} + +func sendHeartbeatWithPrintStatus(conn *websocket.Conn, writeMu *sync.Mutex, moonrakerURL *url.URL, ui *uiTarget, controlMode string, uiAutoDetect bool, cameras []cameraConfig, statusStore *agentStatusStore, printerID string, serverURL string, printStatus *protocol.PrintStatus) error { + health := collectHealth(moonrakerURL, ui, controlMode, uiAutoDetect, cameras, printStatus) + msg := protocol.Message{ + ID: fmt.Sprintf("heartbeat-%d", health.CheckedAtUnix), + Type: protocol.MessageHeartbeat, + Health: &health, + } + if err := writeJSONLocked(conn, writeMu, msg); err != nil { + log.Printf("failed to write heartbeat: %v", err) + return err + } + if statusStore != nil { + if err := statusStore.recordHeartbeat(agentStatusRecord{ + PrinterID: printerID, + ServerURL: serverURL, + MoonrakerURL: moonrakerURL.String(), + AgentVersion: agentVersion, + ControlMode: controlMode, + UIURL: health.UIURL, + UIAutoDetect: uiAutoDetect, + UIReachable: health.UIReachable, + UISource: health.UISource, + MoonrakerReachable: health.MoonrakerReachable, + MoonrakerState: health.MoonrakerState, + MoonrakerMessage: health.MoonrakerMessage, + PrintStatus: health.PrintStatus, + LastHeartbeatAt: time.Unix(health.CheckedAtUnix, 0).UTC(), + Cameras: cameras, + }); err != nil { + log.Printf("failed to write agent status: %v", err) + } + } + return nil +} + +func isActivePrintStatus(status *protocol.PrintStatus) bool { + if status == nil { + return false + } + switch strings.ToLower(strings.TrimSpace(status.State)) { + case "printing", "paused": + return true + default: + return false + } +} + +func collectHealth(moonrakerURL *url.URL, ui *uiTarget, controlMode string, uiAutoDetect bool, cameras []cameraConfig, printStatus *protocol.PrintStatus) protocol.Health { + hostname, _ := os.Hostname() + health := protocol.Health{ + AgentVersion: agentVersion, + Hostname: hostname, + MoonrakerURL: moonrakerURL.String(), + UIAutoDetect: uiAutoDetect, + ControlMode: controlMode, + CheckedAtUnix: time.Now().Unix(), + } + if printStatus != nil { + health.PrintStatus = printStatus + } + if ui != nil && ui.URL != nil { + health.UIURL = ui.URL.String() + health.UIReachable = ui.Reachable + health.UISource = ui.Source + } + for _, camera := range cameras { + if camera.Name == "" { + continue + } + health.Cameras = append(health.Cameras, protocol.CameraHealth{ + Name: camera.Name, + Source: camera.Source, + Service: camera.Service, + Location: camera.Location, + AspectRatio: camera.AspectRatio, + Rotation: camera.Rotation, + FlipHorizontal: camera.FlipHorizontal, + FlipVertical: camera.FlipVertical, + HasSnapshot: camera.SnapshotURL != "", + HasStream: camera.StreamURL != "", + }) + } + + target := *moonrakerURL + target.Path = joinURLPath(moonrakerURL.Path, "/printer/info") + target.RawQuery = "" + + client := &http.Client{Timeout: 5 * time.Second} + resp, err := client.Get(target.String()) + if err != nil { + health.MoonrakerMessage = err.Error() + return health + } + defer resp.Body.Close() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + health.MoonrakerMessage = resp.Status + return health + } + + var body struct { + Result struct { + State string `json:"state"` + StateMessage string `json:"state_message"` + } `json:"result"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&body); err != nil { + health.MoonrakerMessage = err.Error() + return health + } + + health.MoonrakerReachable = true + health.MoonrakerState = body.Result.State + health.MoonrakerMessage = body.Result.StateMessage + return health +} + +func collectPrintStatus(moonrakerURL *url.URL) *protocol.PrintStatus { + target := *moonrakerURL + target.Path = joinURLPath(moonrakerURL.Path, "/printer/objects/query") + target.RawQuery = "print_stats&display_status&gcode_move&toolhead" + + client := &http.Client{Timeout: 5 * time.Second} + rawResult := fetchMoonrakerJSON(client, &target) + rawStatus := moonrakerObjectStatus(rawResult) + if rawStatus == nil { + return nil + } + printStatus := printStatusFromMoonrakerStatus(rawStatus) + if printStatus == nil { + return nil + } + printStatus.MoonrakerMetadataFilename = printStatus.Filename + rawStatus["moonraker_metadata_filename"] = printStatus.Filename + if metadata := collectPrintMetadata(moonrakerURL, printStatus.Filename); metadata != nil { + rawStatus["moonraker_metadata"] = metadata + printStatus.MoonrakerMetadata = metadata + } + return printStatus +} + +func printStatusFromMoonrakerStatus(rawStatus map[string]any) *protocol.PrintStatus { + if rawStatus == nil { + return nil + } + status, ok := rawStatus["print_stats"].(map[string]any) + if !ok { + return nil + } + printStatus := &protocol.PrintStatus{ + MoonrakerStatus: rawStatus, + } + if state, _ := status["state"].(string); state != "" { + printStatus.State = state + } + if filename, _ := status["filename"].(string); filename != "" { + printStatus.Filename = filename + } + if message, _ := status["message"].(string); message != "" { + printStatus.Message = message + } + if progress, ok := rawStatus["display_status"].(map[string]any); ok { + if value, ok := progress["progress"].(float64); ok { + printStatus.Progress = value + } + if message, _ := progress["message"].(string); message != "" && printStatus.Message == "" { + printStatus.Message = message + } + } + if value, ok := status["print_duration"].(float64); ok { + printStatus.PrintDuration = value + } + if value, ok := status["total_duration"].(float64); ok { + printStatus.TotalDuration = value + } + if value, ok := status["filament_used"].(float64); ok { + printStatus.FilamentUsed = value + } + if value, ok := status["estimated_time_remaining"].(float64); ok { + printStatus.EstimatedTimeRemaining = value + } + currentLayer, totalLayer := 0, 0 + if info, ok := status["info"].(map[string]any); ok { + if value, ok := info["current_layer"]; ok { + if layer, ok := jsonNumberToInt(value); ok { + currentLayer = layer + } + } + if value, ok := info["total_layer"]; ok { + if layer, ok := jsonNumberToInt(value); ok { + totalLayer = layer + } + } + } + if currentLayer > 0 { + printStatus.CurrentLayer = currentLayer + } + if totalLayer > 0 { + printStatus.TotalLayer = totalLayer + } + if printStatus.LayerSource == "" { + if printStatus.CurrentLayer > 0 || printStatus.TotalLayer > 0 { + printStatus.LayerSource = "print_stats" + } + } + if metadata, ok := rawStatus["moonraker_metadata"].(map[string]any); ok { + printStatus.MoonrakerMetadata = metadata + } + if metadataFilename, _ := rawStatus["moonraker_metadata_filename"].(string); metadataFilename != "" { + printStatus.MoonrakerMetadataFilename = metadataFilename + } + return printStatus +} + +func (c *moonrakerStatusCache) update(partial map[string]any) (*protocol.PrintStatus, bool, bool) { + if c == nil || partial == nil { + return nil, false, false + } + c.mu.Lock() + defer c.mu.Unlock() + if c.status == nil { + c.status = map[string]any{} + } + mergeMoonrakerStatus(c.status, partial) + c.updatedAt = time.Now().UTC() + status := printStatusFromMoonrakerStatus(c.status) + key := moonrakerSubscriptionStatusKey(c.status) + if key == "" || key == c.key { + return status, false, false + } + c.key = key + logUpdate := moonrakerSubscriptionUpdateShouldLog(partial, status, c.lastLogAt) + if logUpdate { + c.lastLogAt = c.updatedAt + } + return status, true, logUpdate +} + +func (c *moonrakerStatusCache) seed(status *protocol.PrintStatus) { + if c == nil || status == nil { + return + } + c.mu.Lock() + if c.status == nil { + c.status = map[string]any{} + } + c.status["print_stats"] = map[string]any{ + "state": status.State, + "filename": status.Filename, + "message": status.Message, + "progress": status.Progress, + "print_duration": status.PrintDuration, + "total_duration": status.TotalDuration, + "filament_used": status.FilamentUsed, + "estimated_time_remaining": status.EstimatedTimeRemaining, + "info": map[string]any{ + "current_layer": status.CurrentLayer, + "total_layer": status.TotalLayer, + }, + } + if status.MoonrakerStatus != nil { + for key, value := range status.MoonrakerStatus { + c.status[key] = value + } + } + if status.MoonrakerMetadata != nil { + c.status["moonraker_metadata"] = status.MoonrakerMetadata + } + if status.MoonrakerMetadataFilename != "" { + c.status["moonraker_metadata_filename"] = status.MoonrakerMetadataFilename + } + c.key = moonrakerSubscriptionStatusKey(c.status) + c.updatedAt = time.Now().UTC() + c.mu.Unlock() +} + +func (c *moonrakerStatusCache) reset() { + if c == nil { + return + } + c.mu.Lock() + c.status = nil + c.key = "" + c.updatedAt = time.Time{} + c.lastLogAt = time.Time{} + c.mu.Unlock() +} + +func (c *moonrakerStatusCache) snapshot(maxAge time.Duration) *protocol.PrintStatus { + if c == nil { + return nil + } + c.mu.Lock() + defer c.mu.Unlock() + if c.status == nil || c.updatedAt.IsZero() { + return nil + } + if maxAge > 0 && time.Since(c.updatedAt) > maxAge { + return nil + } + return printStatusFromMoonrakerStatus(c.status) +} + +func cachedMoonrakerPrintStatus(cache *moonrakerStatusCache, moonrakerURL *url.URL) *protocol.PrintStatus { + if cache == nil { + return nil + } + status := cache.snapshot(45 * time.Second) + if status == nil { + return nil + } + if needsMetadataRefresh(status) { + refreshed := collectPrintStatus(moonrakerURL) + if refreshed != nil { + cache.seed(refreshed) + return refreshed + } + } + return status +} + +func needsMetadataRefresh(status *protocol.PrintStatus) bool { + if status == nil { + return false + } + if strings.TrimSpace(status.Filename) == "" { + return false + } + if strings.TrimSpace(status.MoonrakerMetadataFilename) == "" { + return true + } + return !strings.EqualFold(strings.TrimSpace(status.MoonrakerMetadataFilename), strings.TrimSpace(status.Filename)) +} + +func collectPrintMetadata(moonrakerURL *url.URL, filename string) map[string]any { + filename = strings.TrimSpace(filename) + if filename == "" { + return nil + } + target := *moonrakerURL + target.Path = joinURLPath(moonrakerURL.Path, "/server/files/metadata") + target.RawQuery = "filename=" + url.QueryEscape(filename) + client := &http.Client{Timeout: 5 * time.Second} + result := fetchMoonrakerJSON(client, &target) + if result == nil { + return nil + } + return result +} + +func moonrakerSubscriptionStatusKey(status map[string]any) string { + if len(status) == 0 { + return "" + } + data, err := json.Marshal(status) + if err != nil { + return "" + } + return string(data) +} + +func moonrakerSubscriptionUpdateShouldLog(partial map[string]any, status *protocol.PrintStatus, lastLogAt time.Time) bool { + if status == nil { + return false + } + if lastLogAt.IsZero() || time.Since(lastLogAt) > 30*time.Second { + return true + } + for _, key := range mapKeys(partial) { + switch key { + case "print_stats", "display_status", "gcode_move", "toolhead": + return true + } + } + return false +} + +func mergeMoonrakerStatus(dst map[string]any, src map[string]any) { + for key, value := range src { + if srcMap, ok := value.(map[string]any); ok { + if dstMap, ok := dst[key].(map[string]any); ok { + mergeMoonrakerStatus(dstMap, srcMap) + continue + } + } + dst[key] = value + } +} + +func moonrakerSubscriptionLoop(done <-chan struct{}, subscriptionReady chan<- struct{}, conn *websocket.Conn, writeMu *sync.Mutex, moonrakerURL *url.URL, state *runtimeState, store *cameraStore, statusStore *agentStatusStore, cache *moonrakerStatusCache, printerID string, serverURL string) { + var readyOnce sync.Once + ready := func() { + readyOnce.Do(func() { + if subscriptionReady != nil { + close(subscriptionReady) + } + }) + } + backoff := time.Second + for { + if cache != nil { + cache.reset() + } + err := runMoonrakerSubscription(done, ready, conn, writeMu, moonrakerURL, state, store, statusStore, cache, printerID, serverURL) + select { + case <-done: + ready() + return + default: + } + if err != nil { + log.Printf("moonraker subscription stopped: %v; reconnecting in %s", err, backoff) + } + select { + case <-time.After(backoff): + case <-done: + return + } + if backoff < 30*time.Second { + backoff *= 2 + if backoff > 30*time.Second { + backoff = 30 * time.Second + } + } + } +} + +func runMoonrakerSubscription(done <-chan struct{}, ready func(), conn *websocket.Conn, writeMu *sync.Mutex, moonrakerURL *url.URL, state *runtimeState, store *cameraStore, statusStore *agentStatusStore, cache *moonrakerStatusCache, printerID string, serverURL string) error { + if cache == nil { + cache = &moonrakerStatusCache{} + } + target := moonrakerWebSocketURL(moonrakerURL) + upstream, _, err := websocket.DefaultDialer.Dial(target.String(), nil) + if err != nil { + return err + } + defer upstream.Close() + if ready != nil { + ready() + } + go func() { + <-done + _ = upstream.Close() + }() + + objects, err := moonrakerSubscriptionObjectNames(upstream) + if err != nil { + log.Printf("moonraker object discovery failed: %v", err) + } + if len(objects) == 0 { + objects = defaultMoonrakerSubscriptionObjects() + } + log.Printf("moonraker subscription objects printer_id=%s objects=%v", printerID, objects) + + subscriptionObjects := make(map[string]any, len(objects)) + for _, object := range objects { + subscriptionObjects[object] = nil + } + if err := upstream.WriteJSON(map[string]any{ + "jsonrpc": "2.0", + "method": "printer.objects.subscribe", + "params": map[string]any{ + "objects": subscriptionObjects, + }, + "id": 2, + }); err != nil { + return err + } + + for { + select { + case <-done: + return nil + default: + } + var msg map[string]any + if err := upstream.ReadJSON(&msg); err != nil { + return err + } + partial := moonrakerSubscriptionStatus(msg) + if partial == nil { + continue + } + printStatus, changed, logUpdate := cache.update(partial) + if !changed { + continue + } + if logUpdate { + log.Printf("moonraker subscription update printer_id=%s keys=%v layers=%d/%d", printerID, mapKeys(partial), printStatus.CurrentLayer, printStatus.TotalLayer) + } + if err := sendHeartbeatWithPrintStatus(conn, writeMu, moonrakerURL, state.snapshotUI(), state.snapshotControlMode(), state.snapshotUIAutoDetect(), store.snapshot(), statusStore, printerID, serverURL, printStatus); err != nil { + return err + } + } +} + +func moonrakerSubscriptionObjectNames(conn *websocket.Conn) ([]string, error) { + if conn == nil { + return nil, fmt.Errorf("moonraker websocket unavailable") + } + if err := conn.WriteJSON(map[string]any{ + "jsonrpc": "2.0", + "method": "printer.objects.list", + "id": 1, + }); err != nil { + return nil, err + } + for { + var msg map[string]any + if err := conn.ReadJSON(&msg); err != nil { + return nil, err + } + if id, ok := jsonNumberToInt(msg["id"]); !ok || id != 1 { + continue + } + if names := moonrakerObjectNamesFromResultAny(msg["result"]); len(names) > 0 { + return selectMoonrakerSubscriptionObjects(names), nil + } + return nil, fmt.Errorf("moonraker object list missing objects (%T)", msg["result"]) + } +} + +func moonrakerObjectNamesFromResult(result map[string]any) []string { + if len(result) == 0 { + return nil + } + if rawObjects, ok := result["objects"].([]any); ok { + names := make([]string, 0, len(rawObjects)) + for _, raw := range rawObjects { + name, _ := raw.(string) + name = strings.TrimSpace(name) + if name == "" { + continue + } + names = append(names, name) + } + return names + } + if rawObjects, ok := result["objects"].([]string); ok { + names := make([]string, 0, len(rawObjects)) + for _, name := range rawObjects { + name = strings.TrimSpace(name) + if name == "" { + continue + } + names = append(names, name) + } + return names + } + return nil +} + +func waitForMoonrakerSubscription(subscriptionReady <-chan struct{}) { + if subscriptionReady == nil { + return + } + select { + case <-subscriptionReady: + case <-time.After(moonrakerSubscriptionStartupTimeout): + } +} + +func moonrakerObjectNamesFromResultAny(result any) []string { + switch v := result.(type) { + case map[string]any: + return moonrakerObjectNamesFromResult(v) + case []any: + names := make([]string, 0, len(v)) + for _, raw := range v { + name, _ := raw.(string) + name = strings.TrimSpace(name) + if name == "" { + continue + } + names = append(names, name) + } + return names + case []string: + names := make([]string, 0, len(v)) + for _, name := range v { + name = strings.TrimSpace(name) + if name == "" { + continue + } + names = append(names, name) + } + return names + } + return nil +} + +func defaultMoonrakerSubscriptionObjects() []string { + return []string{ + "print_stats", + "display_status", + "gcode_move", + "toolhead", + "extruder", + "heater_bed", + "fan", + } +} + +func selectMoonrakerSubscriptionObjects(available []string) []string { + if len(available) == 0 { + return defaultMoonrakerSubscriptionObjects() + } + wanted := map[string]struct{}{ + "print_stats": {}, + "display_status": {}, + "gcode_move": {}, + "toolhead": {}, + "extruder": {}, + "heater_bed": {}, + "fan": {}, + } + prefixes := []string{ + "extruder", + "temperature_sensor ", + "temperature_fan ", + "controller_fan ", + "fan_generic ", + "heater_fan ", + } + selected := make([]string, 0, len(wanted)+8) + seen := map[string]struct{}{} + for _, name := range available { + name = strings.TrimSpace(name) + if name == "" { + continue + } + if _, ok := wanted[name]; ok { + if _, seenAlready := seen[name]; !seenAlready { + selected = append(selected, name) + seen[name] = struct{}{} + } + continue + } + for _, prefix := range prefixes { + if strings.HasPrefix(name, prefix) { + if _, seenAlready := seen[name]; !seenAlready { + selected = append(selected, name) + seen[name] = struct{}{} + } + break + } + } + } + if len(selected) == 0 { + return defaultMoonrakerSubscriptionObjects() + } + sort.Strings(selected) + return selected +} + +func mapKeys(values map[string]any) []string { + if len(values) == 0 { + return nil + } + keys := make([]string, 0, len(values)) + for key := range values { + keys = append(keys, key) + } + sort.Strings(keys) + return keys +} + +func moonrakerWebSocketURL(moonrakerURL *url.URL) *url.URL { + target := *moonrakerURL + if target.Scheme == "https" { + target.Scheme = "wss" + } else { + target.Scheme = "ws" + } + target.Path = joinURLPath(moonrakerURL.Path, "/websocket") + target.RawQuery = "" + return &target +} + +func moonrakerSubscriptionStatus(msg map[string]any) map[string]any { + if msg == nil { + return nil + } + if result, ok := msg["result"].(map[string]any); ok { + if status, ok := result["status"].(map[string]any); ok { + return status + } + } + if method, _ := msg["method"].(string); method != "notify_status_update" { + return nil + } + params, ok := msg["params"].([]any) + if !ok || len(params) == 0 { + return nil + } + status, _ := params[0].(map[string]any) + return status +} + +func moonrakerObjectStatus(result map[string]any) map[string]any { + if result == nil { + return nil + } + if status, ok := result["status"].(map[string]any); ok { + return status + } + return result +} + +func fetchMoonrakerJSON(client *http.Client, target *url.URL) map[string]any { + resp, err := client.Get(target.String()) + if err != nil { + return nil + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil + } + var body map[string]any + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&body); err != nil { + return nil + } + if result, ok := body["result"].(map[string]any); ok { + return result + } + return body +} + +func jsonNumberToInt(value any) (int, bool) { + switch v := value.(type) { + case float64: + return int(v), true + case float32: + return int(v), true + case int: + return v, true + case int32: + return int(v), true + case int64: + return int(v), true + case json.Number: + if n, err := v.Int64(); err == nil { + return int(n), true + } + if f, err := v.Float64(); err == nil { + return int(f), true + } + } + return 0, false +} + +func discoverCameras(moonrakerURL *url.URL, configured []cameraConfig) []cameraConfig { + discovered := fetchMoonrakerCameras(moonrakerURL) + if len(discovered) == 0 { + return configured + } + + merged := make(map[string]cameraConfig, len(configured)+len(discovered)) + order := make([]string, 0, len(configured)+len(discovered)) + for _, camera := range discovered { + if camera.Name == "" { + continue + } + merged[camera.Name] = camera + order = append(order, camera.Name) + } + for _, camera := range configured { + if camera.Name == "" { + continue + } + if _, exists := merged[camera.Name]; !exists { + order = append(order, camera.Name) + } + merged[camera.Name] = mergeCamera(merged[camera.Name], camera) + } + + cameras := make([]cameraConfig, 0, len(order)) + for _, name := range order { + cameras = append(cameras, merged[name]) + } + return cameras +} + +func fetchMoonrakerCameras(moonrakerURL *url.URL) []cameraConfig { + target := *moonrakerURL + target.Path = joinURLPath(moonrakerURL.Path, "/server/webcams/list") + target.RawQuery = "" + + client := &http.Client{Timeout: 5 * time.Second} + resp, err := client.Get(target.String()) + if err != nil { + return nil + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil + } + + var body struct { + Result struct { + Webcams []struct { + Name string `json:"name"` + Enabled bool `json:"enabled"` + SnapshotURL string `json:"snapshot_url"` + StreamURL string `json:"stream_url"` + Source string `json:"source"` + Service string `json:"service"` + Location string `json:"location"` + AspectRatio string `json:"aspect_ratio"` + Rotation int `json:"rotation"` + FlipHorizontal bool `json:"flip_horizontal"` + FlipVertical bool `json:"flip_vertical"` + } `json:"webcams"` + } `json:"result"` + Webcams []struct { + Name string `json:"name"` + Enabled bool `json:"enabled"` + SnapshotURL string `json:"snapshot_url"` + StreamURL string `json:"stream_url"` + Source string `json:"source"` + Service string `json:"service"` + Location string `json:"location"` + AspectRatio string `json:"aspect_ratio"` + Rotation int `json:"rotation"` + FlipHorizontal bool `json:"flip_horizontal"` + FlipVertical bool `json:"flip_vertical"` + } `json:"webcams"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&body); err != nil { + return nil + } + + webcams := body.Result.Webcams + if len(webcams) == 0 { + webcams = body.Webcams + } + + cameras := make([]cameraConfig, 0, len(webcams)) + for _, webcam := range webcams { + if webcam.Name == "" || !webcam.Enabled { + continue + } + cameras = append(cameras, cameraConfig{ + Name: webcam.Name, + SnapshotURL: resolveCameraURL(moonrakerURL, webcam.SnapshotURL), + StreamURL: resolveCameraURL(moonrakerURL, webcam.StreamURL), + Source: webcam.Source, + Service: webcam.Service, + Location: webcam.Location, + AspectRatio: webcam.AspectRatio, + Rotation: webcam.Rotation, + FlipHorizontal: webcam.FlipHorizontal, + FlipVertical: webcam.FlipVertical, + }) + } + for i := range cameras { + cameras[i] = resolveMoonrakerCameraTest(moonrakerURL, cameras[i]) + } + return cameras +} + +func resolveMoonrakerCameraTest(moonrakerURL *url.URL, camera cameraConfig) cameraConfig { + target := *moonrakerURL + target.Path = joinURLPath(moonrakerURL.Path, "/server/webcams/test") + target.RawQuery = url.Values{"name": []string{camera.Name}}.Encode() + + client := &http.Client{Timeout: 5 * time.Second} + req, err := http.NewRequest(http.MethodPost, target.String(), nil) + if err != nil { + return camera + } + resp, err := client.Do(req) + if err != nil { + return camera + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return camera + } + + var body struct { + Result struct { + SnapshotURL string `json:"snapshot_url"` + StreamURL string `json:"stream_url"` + } `json:"result"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&body); err != nil { + return camera + } + if body.Result.SnapshotURL != "" { + camera.SnapshotURL = normalizeDiscoveredCameraURL(moonrakerURL, body.Result.SnapshotURL) + } + if body.Result.StreamURL != "" { + camera.StreamURL = normalizeDiscoveredCameraURL(moonrakerURL, body.Result.StreamURL) + } + return camera +} + +func mergeCamera(base cameraConfig, override cameraConfig) cameraConfig { + if override.Name != "" { + base.Name = override.Name + } + if override.SnapshotURL != "" { + base.SnapshotURL = override.SnapshotURL + } + if override.StreamURL != "" { + base.StreamURL = override.StreamURL + } + if override.Source != "" { + base.Source = override.Source + } + if override.Service != "" { + base.Service = override.Service + } + if override.Location != "" { + base.Location = override.Location + } + if override.AspectRatio != "" { + base.AspectRatio = override.AspectRatio + } + if override.Rotation != 0 { + base.Rotation = override.Rotation + } + if override.FlipHorizontal { + base.FlipHorizontal = true + } + if override.FlipVertical { + base.FlipVertical = true + } + return base +} + +func resolveCameraURL(base *url.URL, raw string) string { + raw = strings.TrimSpace(raw) + if raw == "" { + return "" + } + parsed, err := url.Parse(raw) + if err != nil { + return raw + } + return normalizeDiscoveredCameraURL(base, base.ResolveReference(parsed).String()) +} + +func normalizeDiscoveredCameraURL(base *url.URL, raw string) string { + parsed, err := url.Parse(raw) + if err != nil { + return raw + } + if isLoopbackHost(parsed.Hostname()) && !isLoopbackHost(base.Hostname()) { + host := base.Hostname() + if parsed.Port() != "" { + host += ":" + parsed.Port() + } + parsed.Host = host + } + return parsed.String() +} + +func isLoopbackHost(host string) bool { + switch strings.ToLower(host) { + case "localhost", "127.0.0.1", "::1": + return true + default: + return false + } +} + +func discoverUI(configured string, autoDetect bool, moonrakerURL *url.URL) *uiTarget { + if configured != "" { + u, err := url.Parse(configured) + if err != nil { + log.Printf("invalid ui_url %q: %v", configured, err) + return nil + } + return &uiTarget{URL: u, Source: "config", Reachable: checkUIReachable(u)} + } + if !autoDetect { + return nil + } + for _, candidate := range uiCandidates(moonrakerURL) { + u, err := url.Parse(candidate) + if err != nil { + continue + } + if sameOrigin(u, moonrakerURL) { + continue + } + if checkUIReachable(u) { + return &uiTarget{URL: u, Source: "auto", Reachable: true} + } + } + return nil +} + +func uiCandidates(moonrakerURL *url.URL) []string { + candidates := []string{ + "http://127.0.0.1", + "http://127.0.0.1:80", + "http://127.0.0.1:4408", + "http://127.0.0.1:8080", + } + if moonrakerURL == nil { + return candidates + } + + host := moonrakerURL.Hostname() + if host == "" { + return candidates + } + candidates = append(candidates, + "http://"+host, + "http://"+host+":80", + "http://"+host+":4408", + "http://"+host+":8080", + ) + if moonrakerURL.Scheme == "https" || moonrakerURL.Port() == "443" { + candidates = append(candidates, "https://"+host, "https://"+host+":443") + } + return candidates +} + +func checkUIReachable(base *url.URL) bool { + client := &http.Client{Timeout: 2 * time.Second} + req, err := http.NewRequest(http.MethodGet, base.String(), nil) + if err != nil { + return false + } + req.Header.Set("Accept-Encoding", "identity") + resp, err := client.Do(req) + if err != nil { + return false + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, 16<<10)) + if err != nil { + return false + } + if resp.StatusCode < 200 || resp.StatusCode >= 500 { + return false + } + lower := strings.ToLower(string(body)) + if strings.Contains(lower, "welcome to moonraker") || strings.Contains(lower, "moonraker") || strings.Contains(lower, "mjpg-streamer") { + return false + } + return true +} + +func sameOrigin(a *url.URL, b *url.URL) bool { + if a == nil || b == nil { + return false + } + return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host) +} + +func handleRequest(conn *websocket.Conn, writeMu *sync.Mutex, wsStore *wsStore, moonrakerURL *url.URL, ui *uiTarget, cameras []cameraConfig, stateFile string, msg protocol.Message) { + if msg.Target == "moonraker_ws" { + proxyWebSocket(conn, writeMu, wsStore, moonrakerURL, msg) + return + } + if msg.Target == "ui_ws" { + var uiURL *url.URL + if ui != nil { + uiURL = ui.URL + } + proxyWebSocket(conn, writeMu, wsStore, uiURL, msg) + return + } + if msg.Target == "camera" { + proxyCamera(conn, writeMu, cameras, msg) + return + } + if msg.Target == "camera_snapshot" { + sendCameraSnapshot(conn, writeMu, cameras, msg) + return + } + if msg.Target == "ui" { + var uiURL *url.URL + if ui != nil { + uiURL = ui.URL + } + resp := proxyHTTP(uiURL, msg, 64<<20) + if err := writeJSONLocked(conn, writeMu, resp); err != nil { + log.Printf("failed to write ui response id=%s: %v", msg.ID, err) + } + return + } + if msg.Target == "agent_update" { + if err := performAgentUpdate(conn, writeMu, stateFile, msg); err != nil { + writeError(conn, writeMu, msg.ID, err.Error()) + } + return + } + + resp := proxyMoonraker(moonrakerURL, msg) + + if err := writeJSONLocked(conn, writeMu, resp); err != nil { + log.Printf("failed to write response id=%s: %v", msg.ID, err) + } +} + +func performAgentUpdate(conn *websocket.Conn, writeMu *sync.Mutex, stateFile string, msg protocol.Message) error { + if msg.Update == nil { + return errors.New("missing agent update payload") + } + releaseURL := strings.TrimSpace(msg.Update.ReleaseURL) + if releaseURL == "" { + return errors.New("missing release URL") + } + asset, err := agentAssetForRuntime() + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + binary, err := downloadReleaseAsset(ctx, releaseURL, asset) + if err != nil { + return err + } + exePath, err := os.Executable() + if err != nil { + return err + } + backupPath, err := prepareUpdateBackupPath(stateFile) + if err != nil { + return err + } + if err := copyFile(exePath, backupPath); err != nil { + return fmt.Errorf("failed to back up current agent: %w", err) + } + tempPath := exePath + ".new" + if err := os.WriteFile(tempPath, binary, 0o755); err != nil { + return err + } + if err := os.Rename(tempPath, exePath); err != nil { + _ = os.Remove(tempPath) + return err + } + if err := os.Chmod(exePath, 0o755); err != nil { + return err + } + if err := startRollbackWatchdog(exePath, backupPath, stateFile, msg.Update.Version); err != nil { + log.Printf("failed to start rollback watchdog: %v", err) + } + go func() { + time.Sleep(500 * time.Millisecond) + os.Exit(0) + }() + if err := writeJSONLocked(conn, writeMu, protocol.Message{ + ID: msg.ID, + Type: protocol.MessageHTTPResponse, + Status: http.StatusOK, + Body: base64.StdEncoding.EncodeToString([]byte(`{"ok":true}`)), + }); err != nil { + return err + } + log.Printf("agent update applied asset=%s version=%s", asset, msg.Update.Version) + return nil +} + +func agentAssetForRuntime() (string, error) { + switch runtime.GOARCH { + case "amd64": + return "klipperanywhere-agent-linux-amd64", nil + case "arm64": + return "klipperanywhere-agent-linux-arm64", nil + case "arm": + return "klipperanywhere-agent-linux-armv7", nil + case "mipsle": + return "klipperanywhere-agent-linux-mipsle", nil + default: + return "", fmt.Errorf("unsupported agent architecture: %s", runtime.GOARCH) + } +} + +func downloadReleaseAsset(ctx context.Context, baseURL string, asset string) ([]byte, error) { + baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") + req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/"+asset, nil) + if err != nil { + return nil, err + } + client := &http.Client{Timeout: 2 * time.Minute} + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) + if len(snippet) > 0 { + return nil, fmt.Errorf("download failed: %s: %s", resp.Status, strings.TrimSpace(string(snippet))) + } + return nil, fmt.Errorf("download failed: %s", resp.Status) + } + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + return body, nil +} + +func copyFile(src string, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + return err + } + out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755) + if err != nil { + return err + } + defer out.Close() + if _, err := io.Copy(out, in); err != nil { + return err + } + return out.Sync() +} + +func prepareUpdateBackupPath(stateFile string) (string, error) { + base := filepath.Dir(stateFile) + if base == "." || base == "" { + base = filepath.Dir(defaultStateFile) + } + backupDir := filepath.Join(base, "update-backups") + if err := os.MkdirAll(backupDir, 0o755); err != nil { + return "", err + } + return filepath.Join(backupDir, "klipperanywhere-agent.bak"), nil +} + +func startRollbackWatchdog(targetPath, backupPath, stateFile, expectedVersion string) error { + exePath, err := os.Executable() + if err != nil { + return err + } + devNull, err := os.OpenFile(os.DevNull, os.O_RDWR, 0) + if err != nil { + return err + } + defer devNull.Close() + args := []string{ + exePath, + "rollback-watchdog", + "--target", targetPath, + "--backup", backupPath, + "--state-file", stateFile, + "--expected-version", expectedVersion, + "--timeout", "2m", + } + proc, err := os.StartProcess(exePath, args, &os.ProcAttr{ + Files: []*os.File{devNull, devNull, devNull}, + Env: os.Environ(), + }) + if err != nil { + return err + } + go func() { + _, _ = proc.Wait() + }() + return nil +} + +func runRollbackWatchdog(args []string) error { + fs := flag.NewFlagSet("klipperanywhere-agent rollback-watchdog", flag.ContinueOnError) + var targetPath string + var backupPath string + var stateFile string + var expectedVersion string + var timeout time.Duration + fs.StringVar(&targetPath, "target", "", "path to the agent binary") + fs.StringVar(&backupPath, "backup", "", "path to the backup binary") + fs.StringVar(&stateFile, "state-file", defaultStateFile, "path to the agent state file") + fs.StringVar(&expectedVersion, "expected-version", "", "expected agent version after update") + fs.DurationVar(&timeout, "timeout", 2*time.Minute, "rollback timeout") + if err := fs.Parse(args); err != nil { + return err + } + if targetPath == "" || backupPath == "" { + return errors.New("target and backup are required") + } + time.Sleep(timeout) + status, err := readAgentStatus(stateFile) + if err == nil && strings.TrimSpace(status.AgentVersion) == strings.TrimSpace(expectedVersion) && !status.LastHeartbeatAt.IsZero() { + return nil + } + if err := copyFile(backupPath, targetPath); err != nil { + return fmt.Errorf("rollback restore failed: %w", err) + } + if err := restartAgentService(); err != nil { + return fmt.Errorf("rollback restart failed: %w", err) + } + return nil +} + +func restartAgentService() error { + commands := []string{ + "systemctl restart klipperanywhere-agent", + "rc-service klipperanywhere-agent restart 2>/dev/null || rc-service klipperanywhere-agent start", + "service klipperanywhere-agent restart", + "/etc/init.d/klipperanywhere-agent restart", + } + for _, command := range commands { + if strings.Contains(command, "systemctl") && !(fileExists("/run/systemd/system") || commandExists("systemctl")) { + continue + } + if strings.Contains(command, "rc-service") && !commandExists("rc-service") { + continue + } + if strings.Contains(command, "/etc/init.d/klipperanywhere-agent") && !fileExists("/etc/init.d/klipperanywhere-agent") { + continue + } + out, err := exec.Command("sh", "-lc", command).CombinedOutput() + if err == nil { + return nil + } + if len(out) > 0 { + log.Printf("rollback restart command failed: %s: %s", command, strings.TrimSpace(string(out))) + } + } + return errors.New("no supported service manager found to restart the agent") +} + +func fileExists(path string) bool { + info, err := os.Stat(path) + return err == nil && !info.IsDir() +} + +func commandExists(name string) bool { + _, err := exec.LookPath(name) + return err == nil +} + +func proxyWebSocket(tunnel *websocket.Conn, writeMu *sync.Mutex, store *wsStore, baseURL *url.URL, msg protocol.Message) { + if baseURL == nil { + writeError(tunnel, writeMu, msg.ID, "target is not configured") + return + } + target := *baseURL + if target.Scheme == "https" { + target.Scheme = "wss" + } else { + target.Scheme = "ws" + } + target.Path = joinURLPath(baseURL.Path, msg.Path) + target.RawQuery = "" + if i := strings.Index(msg.Path, "?"); i >= 0 { + target.Path = joinURLPath(baseURL.Path, msg.Path[:i]) + target.RawQuery = msg.Path[i+1:] + } + + upstream, _, err := websocket.DefaultDialer.Dial(target.String(), nil) + if err != nil { + writeError(tunnel, writeMu, msg.ID, err.Error()) + return + } + store.add(msg.ID, upstream) + if err := writeJSONLocked(tunnel, writeMu, protocol.Message{ID: msg.ID, Type: protocol.MessageHTTPResponse, Status: http.StatusSwitchingProtocols}); err != nil { + store.close(msg.ID) + return + } + + go func() { + defer store.close(msg.ID) + for { + messageType, payload, err := upstream.ReadMessage() + if err != nil { + _ = writeJSONLocked(tunnel, writeMu, protocol.Message{ID: msg.ID, Target: "ws_frame", End: true}) + return + } + if messageType != websocket.TextMessage && messageType != websocket.BinaryMessage { + continue + } + _ = writeJSONLocked(tunnel, writeMu, protocol.Message{ + ID: msg.ID, + Target: "ws_frame", + Type: protocol.MessageHTTPResponse, + Body: base64.StdEncoding.EncodeToString(payload), + WSMessageType: messageType, + }) + } + }() +} + +func (s *wsStore) add(id string, conn *websocket.Conn) { + s.mu.Lock() + s.conns[id] = conn + s.mu.Unlock() +} + +func (s *wsStore) write(msg protocol.Message) { + body, err := base64.StdEncoding.DecodeString(msg.Body) + if err != nil { + return + } + s.mu.Lock() + conn := s.conns[msg.ID] + s.mu.Unlock() + if conn == nil { + return + } + if msg.End { + _ = conn.Close() + return + } + messageType := msg.WSMessageType + if messageType != websocket.BinaryMessage && messageType != websocket.TextMessage { + messageType = websocket.TextMessage + } + _ = conn.WriteMessage(messageType, body) +} + +func (s *wsStore) close(id string) { + s.mu.Lock() + conn := s.conns[id] + delete(s.conns, id) + s.mu.Unlock() + if conn != nil { + _ = conn.Close() + } +} + +func proxyCamera(conn *websocket.Conn, writeMu *sync.Mutex, cameras []cameraConfig, msg protocol.Message) { + camera, ok := findCamera(cameras, msg.CameraName) + if !ok { + writeError(conn, writeMu, msg.ID, "camera is not configured") + return + } + + rawURL := camera.SnapshotURL + if msg.CameraKind == "stream" { + rawURL = camera.StreamURL + } + if rawURL == "" { + writeError(conn, writeMu, msg.ID, "camera endpoint is not configured") + return + } + + req, err := http.NewRequest(http.MethodGet, rawURL, nil) + if err != nil { + writeError(conn, writeMu, msg.ID, err.Error()) + return + } + + client := &http.Client{} + if msg.CameraKind != "stream" { + client.Timeout = 15 * time.Second + } + resp, err := client.Do(req) + if err != nil { + writeError(conn, writeMu, msg.ID, err.Error()) + return + } + defer resp.Body.Close() + + header := protocol.Message{ + ID: msg.ID, + Type: protocol.MessageHTTPResponse, + Status: resp.StatusCode, + Headers: headersFromHTTP(resp.Header), + } + if err := writeJSONLocked(conn, writeMu, header); err != nil { + log.Printf("failed to write camera response header id=%s: %v", msg.ID, err) + return + } + + buf := make([]byte, 32*1024) + for { + n, readErr := resp.Body.Read(buf) + if n > 0 { + chunk := protocol.Message{ + ID: msg.ID, + Type: protocol.MessageHTTPResponse, + Body: base64.StdEncoding.EncodeToString(buf[:n]), + } + if err := writeJSONLocked(conn, writeMu, chunk); err != nil { + log.Printf("failed to write camera chunk id=%s: %v", msg.ID, err) + return + } + } + if readErr != nil { + end := protocol.Message{ + ID: msg.ID, + Type: protocol.MessageHTTPResponse, + End: true, + } + if readErr != io.EOF { + end.Type = protocol.MessageError + end.Error = readErr.Error() + } + if err := writeJSONLocked(conn, writeMu, end); err != nil { + log.Printf("failed to write camera end id=%s: %v", msg.ID, err) + } + return + } + } +} + +func sendCameraSnapshot(conn *websocket.Conn, writeMu *sync.Mutex, cameras []cameraConfig, msg protocol.Message) { + camera, ok := findCamera(cameras, msg.CameraName) + if !ok { + writeError(conn, writeMu, msg.ID, "camera is not configured") + return + } + data, headers, status, err := fetchCameraSnapshot(camera) + if err != nil { + writeError(conn, writeMu, msg.ID, err.Error()) + return + } + resp := protocol.Message{ + ID: msg.ID, + Type: protocol.MessageHTTPResponse, + Status: status, + Headers: headers, + Body: base64.StdEncoding.EncodeToString(data), + End: true, + } + if err := writeJSONLocked(conn, writeMu, resp); err != nil { + log.Printf("failed to write camera snapshot response id=%s: %v", msg.ID, err) + } +} + +func fetchCameraSnapshot(camera cameraConfig) ([]byte, []protocol.Header, int, error) { + rawURL := strings.TrimSpace(camera.SnapshotURL) + if rawURL == "" { + return nil, nil, 0, fmt.Errorf("camera snapshot endpoint is not configured") + } + req, err := http.NewRequest(http.MethodGet, rawURL, nil) + if err != nil { + return nil, nil, 0, err + } + client := &http.Client{Timeout: 20 * time.Second} + resp, err := client.Do(req) + if err != nil { + return nil, nil, 0, err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + detail := strings.TrimSpace(string(body)) + if detail != "" { + return nil, headersFromHTTP(resp.Header), resp.StatusCode, fmt.Errorf("camera snapshot failed: %s: %s", resp.Status, detail) + } + return nil, headersFromHTTP(resp.Header), resp.StatusCode, fmt.Errorf("camera snapshot failed: %s", resp.Status) + } + data, err := io.ReadAll(io.LimitReader(resp.Body, 20<<20)) + if err != nil { + return nil, headersFromHTTP(resp.Header), resp.StatusCode, err + } + if len(data) == 0 { + return nil, headersFromHTTP(resp.Header), resp.StatusCode, fmt.Errorf("empty camera snapshot") + } + return data, headersFromHTTP(resp.Header), resp.StatusCode, nil +} + +func writeError(conn *websocket.Conn, writeMu *sync.Mutex, id string, message string) { + if err := writeJSONLocked(conn, writeMu, errorMessage(id, message)); err != nil { + log.Printf("failed to write error id=%s: %v", id, err) + } +} + +func findCamera(cameras []cameraConfig, name string) (cameraConfig, bool) { + for _, camera := range cameras { + if camera.Name == name { + return camera, true + } + } + return cameraConfig{}, false +} + +func writeJSONLocked(conn *websocket.Conn, writeMu *sync.Mutex, msg protocol.Message) error { + writeMu.Lock() + defer writeMu.Unlock() + conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) + return conn.WriteJSON(msg) +} + +func proxyMoonraker(baseURL *url.URL, msg protocol.Message) protocol.Message { + return proxyHTTP(baseURL, msg, 64<<20) +} + +func proxyHTTP(baseURL *url.URL, msg protocol.Message, limit int64) protocol.Message { + if baseURL == nil { + return errorMessage(msg.ID, "target is not configured") + } + body, err := base64.StdEncoding.DecodeString(msg.Body) + if err != nil { + return errorMessage(msg.ID, "invalid request body") + } + + target := *baseURL + target.RawQuery = "" + if i := strings.Index(msg.Path, "?"); i >= 0 { + target.Path = joinURLPath(baseURL.Path, msg.Path[:i]) + target.RawQuery = msg.Path[i+1:] + } else { + target.Path = joinURLPath(baseURL.Path, msg.Path) + } + + req, err := http.NewRequest(msg.Method, target.String(), bytes.NewReader(body)) + if err != nil { + return errorMessage(msg.ID, err.Error()) + } + for _, h := range msg.Headers { + if strings.EqualFold(h.Name, "Accept-Encoding") { + continue + } + for _, v := range h.Values { + req.Header.Add(h.Name, v) + } + } + req.Header.Set("Accept-Encoding", "identity") + + client := &http.Client{Timeout: 30 * time.Second} + httpResp, err := client.Do(req) + if err != nil { + return errorMessage(msg.ID, err.Error()) + } + defer httpResp.Body.Close() + + respBody, err := io.ReadAll(io.LimitReader(httpResp.Body, limit)) + if err != nil { + return errorMessage(msg.ID, err.Error()) + } + + return protocol.Message{ + ID: msg.ID, + Type: protocol.MessageHTTPResponse, + Status: httpResp.StatusCode, + Headers: headersFromHTTP(httpResp.Header), + Body: base64.StdEncoding.EncodeToString(respBody), + } +} + +func errorMessage(id string, message string) protocol.Message { + return protocol.Message{ + ID: id, + Type: protocol.MessageError, + Error: message, + } +} + +func headersFromHTTP(h http.Header) []protocol.Header { + headers := make([]protocol.Header, 0, len(h)) + for name, values := range h { + headers = append(headers, protocol.Header{Name: name, Values: values}) + } + return headers +} + +func withAuthQuery(rawURL, printerID, token string) (string, error) { + u, err := url.Parse(rawURL) + if err != nil { + return "", err + } + q := u.Query() + q.Set("printer_id", printerID) + q.Set("token", token) + u.RawQuery = q.Encode() + return u.String(), nil +} + +func joinURLPath(basePath, requestPath string) string { + basePath = strings.TrimRight(basePath, "/") + requestPath = "/" + strings.TrimLeft(requestPath, "/") + if basePath == "" { + return requestPath + } + return basePath + requestPath +} + +func init() { + log.SetFlags(log.LstdFlags | log.Lmicroseconds) +} diff --git a/cmd/agent/main_test.go b/cmd/agent/main_test.go new file mode 100644 index 0000000..1c638f8 --- /dev/null +++ b/cmd/agent/main_test.go @@ -0,0 +1,452 @@ +package main + +import ( + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "net/url" + "testing" + "time" + + "github.com/klipperanywhere/klipperanywhere/internal/protocol" +) + +func TestResolveCameraURL(t *testing.T) { + base, err := url.Parse("http://192.168.1.60:7125") + if err != nil { + t.Fatal(err) + } + + got := resolveCameraURL(base, "/webcam/?action=snapshot") + want := "http://192.168.1.60:7125/webcam/?action=snapshot" + if got != want { + t.Fatalf("resolved url = %q, want %q", got, want) + } +} + +func TestNormalizeDiscoveredCameraURLRewritesLoopback(t *testing.T) { + base, err := url.Parse("http://192.168.1.60:7125") + if err != nil { + t.Fatal(err) + } + + got := normalizeDiscoveredCameraURL(base, "http://127.0.0.1:80/webcam/?action=snapshot") + want := "http://192.168.1.60:80/webcam/?action=snapshot" + if got != want { + t.Fatalf("normalized url = %q, want %q", got, want) + } +} + +func TestFetchMoonrakerCameras(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/server/webcams/list": + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "webcams": []map[string]any{ + { + "name": "Camera", + "enabled": true, + "stream_url": "/webcam/?action=stream", + "snapshot_url": "/webcam/?action=snapshot", + "aspect_ratio": "4:3", + "service": "mjpegstreamer-adaptive", + "location": "printer", + "source": "database", + "flip_horizontal": true, + }, + }, + }, + }) + case "/server/webcams/test": + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "name": "Camera", + "snapshot_url": "http://127.0.0.1:80/webcam/?action=snapshot", + "stream_url": "http://127.0.0.1:80/webcam/?action=stream", + }, + }) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + base, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + cameras := fetchMoonrakerCameras(base) + if len(cameras) != 1 { + t.Fatalf("camera count = %d, want 1", len(cameras)) + } + camera := cameras[0] + if camera.Name != "Camera" { + t.Fatalf("camera name = %q, want Camera", camera.Name) + } + if camera.AspectRatio != "4:3" || camera.Service != "mjpegstreamer-adaptive" || !camera.FlipHorizontal { + t.Fatalf("camera metadata not preserved: %+v", camera) + } + if camera.SnapshotURL == "" || camera.StreamURL == "" { + t.Fatalf("camera urls not populated: %+v", camera) + } +} + +func TestFetchCameraSnapshot(t *testing.T) { + snapshot := []byte{0x01, 0x02, 0x03, 0x04} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/snapshot.jpg" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "image/jpeg") + _, _ = w.Write(snapshot) + })) + defer server.Close() + + data, headers, status, err := fetchCameraSnapshot(cameraConfig{SnapshotURL: server.URL + "/snapshot.jpg"}) + if err != nil { + t.Fatalf("fetchCameraSnapshot returned error: %v", err) + } + if status != http.StatusOK { + t.Fatalf("status = %d, want 200", status) + } + if string(data) != string(snapshot) { + t.Fatalf("snapshot = %x, want %x", data, snapshot) + } + if len(headers) == 0 { + t.Fatal("expected response headers") + } +} + +func TestDiscoverUIUsesConfiguredURL(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("ok")) + })) + defer server.Close() + + ui := discoverUI(server.URL, true, nil) + if ui == nil { + t.Fatal("expected configured ui to be discovered") + } + if ui.URL.String() != server.URL || ui.Source != "config" || !ui.Reachable { + t.Fatalf("unexpected ui target: %+v", ui) + } +} + +func TestDiscoverUIAutoDetectsCommonPort(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:4408") + if err != nil { + t.Skipf("127.0.0.1:4408 unavailable: %v", err) + } + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("ok")) + })) + server.Listener = listener + server.Start() + defer server.Close() + + moonrakerURL, err := url.Parse("http://127.0.0.1:7125") + if err != nil { + t.Fatal(err) + } + ui := discoverUI("", true, moonrakerURL) + if ui == nil { + t.Fatal("expected auto-detected ui") + } + if ui.URL.String() != "http://127.0.0.1:4408" || ui.Source != "auto" || !ui.Reachable { + t.Fatalf("unexpected auto ui target: %+v", ui) + } +} + +func TestIsActivePrintStatus(t *testing.T) { + for _, state := range []string{"printing", "paused", " Printing "} { + if !isActivePrintStatus(&protocol.PrintStatus{State: state}) { + t.Fatalf("state %q should be active", state) + } + } + for _, state := range []string{"", "standby", "complete", "error"} { + if isActivePrintStatus(&protocol.PrintStatus{State: state}) { + t.Fatalf("state %q should not be active", state) + } + } + if isActivePrintStatus(nil) { + t.Fatal("nil status should not be active") + } +} + +func TestMoonrakerSubscriptionStatus(t *testing.T) { + initial := map[string]any{ + "result": map[string]any{ + "status": map[string]any{ + "print_stats": map[string]any{"state": "printing"}, + }, + }, + } + if got := moonrakerSubscriptionStatus(initial); got == nil { + t.Fatal("expected initial subscription status") + } + + update := map[string]any{ + "method": "notify_status_update", + "params": []any{ + map[string]any{ + "print_stats": map[string]any{ + "info": map[string]any{"current_layer": 2}, + }, + }, + 123.4, + }, + } + got := moonrakerSubscriptionStatus(update) + if got == nil { + t.Fatal("expected notify_status_update status") + } + printStats, ok := got["print_stats"].(map[string]any) + if !ok { + t.Fatalf("missing print_stats: %+v", got) + } + info, ok := printStats["info"].(map[string]any) + if !ok || info["current_layer"] != 2 { + t.Fatalf("unexpected subscription info: %+v", got) + } + + if got := moonrakerSubscriptionStatus(map[string]any{"method": "server.info"}); got != nil { + t.Fatalf("non-status message returned %+v", got) + } +} + +func TestMoonrakerStatusCacheMergesPartialLayerUpdates(t *testing.T) { + cache := &moonrakerStatusCache{} + status, changed, _ := cache.update(map[string]any{ + "print_stats": map[string]any{ + "state": "printing", + "filename": "benchy.gcode", + "info": map[string]any{ + "current_layer": 1, + "total_layer": 5, + }, + }, + }) + if !changed || status == nil { + t.Fatalf("initial status changed=%t status=%+v, want changed status", changed, status) + } + if status.CurrentLayer != 1 || status.TotalLayer != 5 { + t.Fatalf("initial layers = %d/%d, want 1/5", status.CurrentLayer, status.TotalLayer) + } + + status, changed, _ = cache.update(map[string]any{ + "print_stats": map[string]any{ + "info": map[string]any{ + "current_layer": 2, + }, + }, + }) + if !changed || status == nil { + t.Fatalf("layer update changed=%t status=%+v, want changed status", changed, status) + } + if status.State != "printing" || status.Filename != "benchy.gcode" { + t.Fatalf("partial update lost print identity: %+v", status) + } + if status.CurrentLayer != 2 || status.TotalLayer != 5 { + t.Fatalf("merged layers = %d/%d, want 2/5", status.CurrentLayer, status.TotalLayer) + } + + _, changed, _ = cache.update(map[string]any{ + "display_status": map[string]any{"progress": 0.42}, + }) + if !changed { + t.Fatal("progress-only update should trigger notification heartbeat") + } +} + +func TestMoonrakerStatusCacheSnapshotAndReset(t *testing.T) { + cache := &moonrakerStatusCache{} + if got := cache.snapshot(time.Second); got != nil { + t.Fatalf("expected empty cache snapshot to be nil, got %+v", got) + } + cache.update(map[string]any{ + "print_stats": map[string]any{ + "state": "printing", + "filename": "benchy.gcode", + }, + }) + if got := cache.snapshot(time.Minute); got == nil || got.State != "printing" || got.Filename != "benchy.gcode" { + t.Fatalf("unexpected cached snapshot: %+v", got) + } + cache.reset() + if got := cache.snapshot(time.Minute); got != nil { + t.Fatalf("expected reset cache snapshot to be nil, got %+v", got) + } +} + +func TestSelectMoonrakerSubscriptionObjects(t *testing.T) { + selected := selectMoonrakerSubscriptionObjects([]string{ + "toolhead", + "fan", + "temperature_sensor chamber", + "display_status", + "heater_bed", + "gcode_move", + "print_stats", + "controller_fan case", + "bed_mesh", + }) + for _, want := range []string{"print_stats", "display_status", "gcode_move", "toolhead", "heater_bed", "fan", "temperature_sensor chamber", "controller_fan case"} { + found := false + for _, got := range selected { + if got == want { + found = true + break + } + } + if !found { + t.Fatalf("selected objects missing %q: %+v", want, selected) + } + } +} + +func TestCollectPrintStatusIncludesLayerFields(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/printer/objects/query" { + http.NotFound(w, r) + return + } + if got := r.URL.RawQuery; got != "print_stats&display_status&gcode_move&toolhead" { + t.Fatalf("unexpected query = %q", got) + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "status": map[string]any{ + "print_stats": map[string]any{ + "state": "printing", + "filename": "benchy.gcode", + "message": "Layer change", + "print_duration": 123.5, + "total_duration": 456.5, + "filament_used": 789.5, + "estimated_time_remaining": 321.5, + "info": map[string]any{ + "current_layer": 2, + "total_layer": 4, + }, + }, + "display_status": map[string]any{ + "progress": 0.42, + "message": "Printing benchy", + }, + }, + }, + }) + })) + defer server.Close() + + base, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + + got := collectPrintStatus(base) + if got == nil { + t.Fatal("expected print status to be collected") + } + if got.State != "printing" { + t.Fatalf("state = %q, want printing", got.State) + } + if got.Filename != "benchy.gcode" { + t.Fatalf("filename = %q, want benchy.gcode", got.Filename) + } + if got.CurrentLayer != 2 { + t.Fatalf("current_layer = %d, want 2", got.CurrentLayer) + } + if got.TotalLayer != 4 { + t.Fatalf("total_layer = %d, want 4", got.TotalLayer) + } + if got.Progress != 0.42 { + t.Fatalf("progress = %v, want 0.42", got.Progress) + } + if got.MoonrakerStatus == nil { + t.Fatal("expected raw moonraker status to be preserved") + } + if _, ok := got.MoonrakerStatus["display_status"].(map[string]any); !ok { + t.Fatalf("raw moonraker status missing display_status: %+v", got.MoonrakerStatus) + } +} + +func TestCollectPrintStatusDoesNotUseMetadataForLayers(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/printer/objects/query", func(w http.ResponseWriter, r *http.Request) { + if got := r.URL.RawQuery; got != "print_stats&display_status&gcode_move&toolhead" { + t.Fatalf("unexpected query = %q", got) + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "status": map[string]any{ + "print_stats": map[string]any{ + "state": "printing", + "filename": "benchy.gcode", + "message": "Layer change", + "print_duration": 123.5, + "total_duration": 456.5, + "filament_used": 789.5, + "estimated_time_remaining": 321.5, + "info": map[string]any{ + "current_layer": 0, + "total_layer": 0, + }, + }, + "display_status": map[string]any{ + "progress": 0.42, + "message": "Printing benchy", + }, + "gcode_move": map[string]any{ + "position": []float64{0, 0, 0.41}, + }, + "toolhead": map[string]any{ + "position": []float64{0, 0, 0.42}, + }, + }, + }, + }) + }) + mux.HandleFunc("/server/files/metadata", func(w http.ResponseWriter, r *http.Request) { + if got := r.URL.Query().Get("filename"); got != "benchy.gcode" { + t.Fatalf("metadata filename = %q, want benchy.gcode", got) + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "metadata": map[string]any{ + "layer_height": 0.2, + "first_layer_height": 0.2, + "object_height": 0.8, + }, + }, + }) + }) + + server := httptest.NewServer(mux) + defer server.Close() + + base, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + + got := collectPrintStatus(base) + if got == nil { + t.Fatal("expected print status to be collected") + } + if got.CurrentLayer != 0 { + t.Fatalf("current_layer = %d, want 0", got.CurrentLayer) + } + if got.TotalLayer != 0 { + t.Fatalf("total_layer = %d, want 0", got.TotalLayer) + } + if got.LayerSource != "" { + t.Fatalf("layer_source = %q, want empty", got.LayerSource) + } + if got.MoonrakerMetadata != nil { + t.Fatalf("moonraker metadata = %+v, want nil", got.MoonrakerMetadata) + } +} diff --git a/cmd/mock-moonraker/main.go b/cmd/mock-moonraker/main.go new file mode 100644 index 0000000..ee00075 --- /dev/null +++ b/cmd/mock-moonraker/main.go @@ -0,0 +1,459 @@ +package main + +import ( + "encoding/json" + "flag" + "fmt" + "log" + "net/http" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +func main() { + var listen string + flag.StringVar(&listen, "listen", ":7125", "address to listen on") + flag.Parse() + + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _, _ = w.Write([]byte(`<!doctype html><html><head><title>Mock UI

Mock Printer UI

`)) + }) + mux.HandleFunc("/assets/app.css", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/css") + _, _ = w.Write([]byte(`body{font-family:sans-serif;background:#111619;color:#f7f3eb}`)) + }) + mux.HandleFunc("/assets/app.js", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/javascript") + _, _ = w.Write([]byte(`fetch("/printer/info").then(r=>r.json()); const wsPath="/websocket"; console.log("mock ui", wsPath);`)) + }) + upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} + mux.HandleFunc("/websocket", func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + defer conn.Close() + var writeMu sync.Mutex + var updatesDone chan struct{} + defer func() { + if updatesDone != nil { + close(updatesDone) + } + }() + for { + messageType, payload, err := conn.ReadMessage() + if err != nil { + return + } + var request map[string]any + if err := json.Unmarshal(payload, &request); err != nil { + _ = conn.WriteMessage(messageType, payload) + continue + } + method, _ := request["method"].(string) + if method == "printer.objects.list" { + response := map[string]any{ + "jsonrpc": "2.0", + "id": request["id"], + "result": map[string]any{ + "objects": mockMoonrakerObjects(), + }, + } + writeMu.Lock() + _ = conn.WriteJSON(response) + writeMu.Unlock() + continue + } + if method == "printer.objects.subscribe" { + requested := mockMoonrakerRequestedObjects(request) + response := map[string]any{ + "jsonrpc": "2.0", + "id": request["id"], + "result": map[string]any{ + "eventtime": time.Now().Unix(), + "status": mockMoonrakerStatus(requested, 0), + }, + } + writeMu.Lock() + _ = conn.WriteJSON(response) + writeMu.Unlock() + if updatesDone == nil { + updatesDone = make(chan struct{}) + go func() { + ticker := time.NewTicker(1 * time.Second) + defer ticker.Stop() + tick := 1 + for { + select { + case <-ticker.C: + update := map[string]any{ + "jsonrpc": "2.0", + "method": "notify_status_update", + "params": []any{ + map[string]any{ + "eventtime": time.Now().Unix(), + "status": mockMoonrakerStatus(requested, tick), + }, + }, + } + writeMu.Lock() + _ = conn.WriteJSON(update) + writeMu.Unlock() + tick++ + case <-updatesDone: + return + } + } + }() + } + continue + } + response := map[string]any{ + "jsonrpc": "2.0", + "result": map[string]any{"echo": method}, + } + if id, ok := request["id"]; ok { + response["id"] = id + } + writeMu.Lock() + _ = conn.WriteJSON(response) + writeMu.Unlock() + } + }) + mux.HandleFunc("/printer/info", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "hostname": "mock-printer", + "software_version": "mock", + "cpu_info": "local-development", + "klipper_path": "/home/pi/klipper", + "python_path": "/home/pi/klippy-env/bin/python", + "log_file": "/tmp/klippy.log", + "config_file": "/tmp/printer.cfg", + }, + }) + }) + mux.HandleFunc("/server/info", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "klippy_connected": true, + "moonraker_version": "mock", + "time": time.Now().Unix(), + }, + }) + }) + mux.HandleFunc("/server/webcams/list", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "webcams": []map[string]any{ + { + "name": "moonraker-default", + "enabled": true, + "stream_url": "/webcam/?action=stream", + "snapshot_url": "/webcam/?action=snapshot", + "aspect_ratio": "16:9", + "rotation": 0, + "location": "printer", + "service": "mjpegstreamer", + "source": "database", + }, + }, + }, + }) + }) + mux.HandleFunc("/server/history/list", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "jobs": []map[string]any{ + { + "filename": "benchy.gcode", + "status": "completed", + "start_time": time.Now().Add(-2 * time.Hour).Unix(), + "end_time": time.Now().Add(-90 * time.Minute).Unix(), + "total_duration": 3600.0, + "print_duration": 3555.0, + "filament_used": 12345.6, + "total_weight": 34.5, + "message": "Completed successfully", + "metadata": map[string]any{"layer_height": 0.2}, + }, + { + "filename": "calibration_cube.gcode", + "status": "cancelled", + "start_time": time.Now().Add(-5 * time.Hour).Unix(), + "end_time": time.Now().Add(-4 * time.Hour).Unix(), + "total_duration": 1800.0, + "print_duration": 1240.0, + "filament_used": 2456.1, + "total_weight": 7.2, + "message": "User cancelled", + }, + }, + }, + }) + }) + mux.HandleFunc("/server/files/metadata", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "filename": r.URL.Query().Get("filename"), + "modified": time.Now().Add(-30 * time.Minute).Unix(), + "size": 4926481, + "filament_name": []string{"Generic PLA Brown", "Generic PETG Blue"}, + "filament_type": []string{"PLA", "PETG"}, + "filament_weights": []float64{18.6, 7.4}, + "referenced_tools": []int{0, 1}, + "filament_weight_total": 26.0, + "mmu_print": 1, + }, + }) + }) + mux.HandleFunc("/server/files/list", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode([]map[string]any{ + { + "path": "benchy.gcode", + "modified": time.Now().Add(-30 * time.Minute).Unix(), + "size": 4926481, + "permissions": "rw", + }, + { + "path": "calibration_cube.gcode", + "modified": time.Now().Add(-2 * time.Hour).Unix(), + "size": 324236, + "permissions": "rw", + }, + { + "path": "nested/test_piece.gcode", + "modified": time.Now().Add(-4 * time.Hour).Unix(), + "size": 1687387, + "permissions": "rw", + }, + }) + }) + mux.HandleFunc("/printer/print/start", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.Header().Set("Allow", "POST") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": "ok", + }) + }) + mux.HandleFunc("/printer/gcode/script", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.Header().Set("Allow", "POST") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": "ok", + }) + }) + mux.HandleFunc("/printer/objects/query", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{ + "status": map[string]any{ + "print_stats": map[string]any{ + "filename": "benchy.gcode", + "state": "printing", + "message": "Printing benchy", + "print_duration": 492.4, + "total_duration": 621.8, + "filament_used": 1234.5, + "estimated_time_remaining": 119.3, + "info": map[string]any{ + "current_layer": 0, + "total_layer": 0, + }, + }, + "display_status": map[string]any{ + "progress": 0.68, + }, + "extruder": map[string]any{ + "temperature": 215.4, + "target": 220.0, + }, + "heater_bed": map[string]any{ + "temperature": 61.2, + "target": 60.0, + }, + "temperature_sensor chamber": map[string]any{ + "temperature": 38.5, + }, + "fan": map[string]any{ + "speed": 0.74, + }, + "fan_generic part_cooling": map[string]any{ + "speed": 0.32, + }, + "gcode_move": map[string]any{ + "position": []float64{0, 0, 0.41, 0}, + }, + "toolhead": map[string]any{ + "position": []float64{0, 0, 0.42}, + }, + }, + }, + }) + }) + mux.HandleFunc("/webcam/", func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Query().Get("action") { + case "snapshot": + writeMockJPEG(w) + case "stream": + writeMockMJPEG(w) + default: + http.NotFound(w, r) + } + }) + + log.Printf("mock moonraker listening on %s", listen) + if err := http.ListenAndServe(listen, mux); err != nil { + log.Fatal(err) + } +} + +func writeMockJPEG(w http.ResponseWriter) { + w.Header().Set("Content-Type", "image/svg+xml") + _, _ = w.Write([]byte(`Mock camera snapshot`)) +} + +func writeMockMJPEG(w http.ResponseWriter) { + w.Header().Set("Content-Type", "multipart/x-mixed-replace; boundary=frame") + flusher, _ := w.(http.Flusher) + for i := 0; i < 120; i++ { + frame := fmt.Sprintf(`Mock camera stream %03d`, 80+(i%32)*12, i) + _, _ = fmt.Fprintf(w, "--frame\r\nContent-Type: image/svg+xml\r\nContent-Length: %d\r\n\r\n%s\r\n", len(frame), frame) + if flusher != nil { + flusher.Flush() + } + time.Sleep(250 * time.Millisecond) + } + _, _ = fmt.Fprint(w, "--frame--\r\n") +} + +func mockMoonrakerObjects() []string { + return []string{ + "webhooks", + "print_stats", + "display_status", + "gcode_move", + "toolhead", + "extruder", + "heater_bed", + "temperature_sensor chamber", + "temperature_fan chamber", + "fan", + "fan_generic part_cooling", + "controller_fan electronics", + } +} + +func mockMoonrakerRequestedObjects(request map[string]any) []string { + params, _ := request["params"].(map[string]any) + requested, _ := params["objects"].(map[string]any) + names := make([]string, 0, len(requested)) + for name := range requested { + names = append(names, name) + } + return names +} + +func mockMoonrakerStatus(requested []string, tick int) map[string]any { + wanted := map[string]struct{}{} + for _, name := range requested { + wanted[name] = struct{}{} + } + status := map[string]any{} + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "print_stats") { + status["print_stats"] = map[string]any{ + "filename": "benchy.gcode", + "state": "printing", + "message": "Printing benchy", + "print_duration": 492.4 + float64(tick), + "total_duration": 621.8 + float64(tick), + "filament_used": 1234.5 + float64(tick)*2, + "estimated_time_remaining": 119.3 - float64(tick), + "info": map[string]any{ + "current_layer": tick + 1, + "total_layer": 12, + }, + } + } + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "display_status") { + status["display_status"] = map[string]any{ + "progress": 0.68 + float64(tick)*0.02, + } + } + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "extruder") { + status["extruder"] = map[string]any{ + "temperature": 215.4 + float64(tick)*1.5, + "target": 220.0, + } + } + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "heater_bed") { + status["heater_bed"] = map[string]any{ + "temperature": 61.2 + float64(tick)*0.8, + "target": 60.0, + } + } + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "temperature_sensor chamber") { + status["temperature_sensor chamber"] = map[string]any{ + "temperature": 38.5 + float64(tick)*0.2, + } + } + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "temperature_fan chamber") { + status["temperature_fan chamber"] = map[string]any{ + "temperature": 42.1 + float64(tick)*0.1, + "speed": 0.55, + } + } + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "fan") { + status["fan"] = map[string]any{ + "speed": 0.74 - float64(tick)*0.01, + } + } + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "fan_generic part_cooling") { + status["fan_generic part_cooling"] = map[string]any{ + "speed": 0.32 + float64(tick)*0.01, + } + } + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "controller_fan electronics") { + status["controller_fan electronics"] = map[string]any{ + "speed": 0.22, + } + } + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "gcode_move") { + status["gcode_move"] = map[string]any{ + "position": []float64{0, 0, 0.41 + float64(tick)*0.01, 0}, + } + } + if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "toolhead") { + status["toolhead"] = map[string]any{ + "position": []float64{0, 0, 0.42 + float64(tick)*0.01}, + } + } + return status +} + +func containsMockMoonrakerObject(set map[string]struct{}, name string) bool { + _, ok := set[name] + return ok +} diff --git a/cmd/server/audit.go b/cmd/server/audit.go new file mode 100644 index 0000000..d58f3a7 --- /dev/null +++ b/cmd/server/audit.go @@ -0,0 +1,151 @@ +package main + +import ( + "bufio" + "encoding/json" + "log" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +type auditStore struct { + path string + mu sync.Mutex +} + +type auditEvent struct { + Timestamp time.Time `json:"timestamp"` + Actor string `json:"actor,omitempty"` + Action string `json:"action"` + PrinterID string `json:"printer_id,omitempty"` + TargetID string `json:"target_id,omitempty"` + Path string `json:"path,omitempty"` + Method string `json:"method,omitempty"` + Detail string `json:"detail,omitempty"` + Status int `json:"status,omitempty"` +} + +func newAuditStore(path string) (*auditStore, error) { + store := &auditStore{path: path} + if path == "" { + return store, nil + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return nil, err + } + return store, nil +} + +func (s *auditStore) append(event auditEvent) error { + if s == nil || s.path == "" { + return nil + } + if event.Timestamp.IsZero() { + event.Timestamp = time.Now().UTC() + } + encoded, err := json.Marshal(event) + if err != nil { + return err + } + + s.mu.Lock() + defer s.mu.Unlock() + + if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil { + return err + } + f, err := os.OpenFile(s.path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) + if err != nil { + return err + } + defer f.Close() + + if _, err := f.Write(append(encoded, '\n')); err != nil { + return err + } + return nil +} + +func (s *auditStore) recent(limit int) ([]auditEvent, error) { + if s == nil || s.path == "" { + return nil, nil + } + if limit <= 0 { + limit = 100 + } + file, err := os.Open(s.path) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, err + } + defer file.Close() + + var events []auditEvent + scanner := bufio.NewScanner(file) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if line == "" { + continue + } + var event auditEvent + if err := json.Unmarshal([]byte(line), &event); err != nil { + continue + } + events = append(events, event) + } + if err := scanner.Err(); err != nil { + return nil, err + } + if len(events) > limit { + events = events[len(events)-limit:] + } + for i, j := 0, len(events)-1; i < j; i, j = i+1, j-1 { + events[i], events[j] = events[j], events[i] + } + return events, nil +} + +func (s *server) logAudit(event auditEvent) { + if s == nil || s.auditLog == nil { + return + } + if err := s.auditLog.append(event); err != nil { + log.Printf("failed to write audit event: %v", err) + } +} + +func actionLabel(action string) string { + switch action { + case "login": + return "login" + case "logout": + return "logout" + case "account_password_change": + return "account_password_change" + case "user_create": + return "user_create" + case "user_update": + return "user_update" + case "user_delete": + return "user_delete" + case "printer_ui_open": + return "printer_ui_open" + case "camera_view": + return "camera_view" + case "printer_http_control": + return "printer_http_control" + case "printer_ws_control": + return "printer_ws_control" + case "printer_ws_blocked": + return "printer_ws_blocked" + case "printer_settings_update": + return "printer_settings_update" + default: + return action + } +} diff --git a/cmd/server/audit_test.go b/cmd/server/audit_test.go new file mode 100644 index 0000000..3f08c7b --- /dev/null +++ b/cmd/server/audit_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "path/filepath" + "testing" + "time" +) + +func TestAuditStoreAppendAndRecent(t *testing.T) { + store, err := newAuditStore(filepath.Join(t.TempDir(), "audit.log")) + if err != nil { + t.Fatal(err) + } + if err := store.append(auditEvent{Actor: "admin", Action: "login", Detail: "successful login"}); err != nil { + t.Fatal(err) + } + if err := store.append(auditEvent{Actor: "admin", Action: "user_update", TargetID: "abc"}); err != nil { + t.Fatal(err) + } + events, err := store.recent(10) + if err != nil { + t.Fatal(err) + } + if len(events) != 2 { + t.Fatalf("events = %+v", events) + } + if events[0].Action != "user_update" || events[1].Action != "login" { + t.Fatalf("unexpected ordering: %+v", events) + } + if events[0].Timestamp.IsZero() || events[1].Timestamp.IsZero() { + t.Fatal("expected timestamps to be populated") + } +} + +func TestActionLabel(t *testing.T) { + if got := actionLabel("camera_view"); got != "camera_view" { + t.Fatalf("actionLabel = %q", got) + } +} + +func TestAuditStoreRecentEmpty(t *testing.T) { + store, err := newAuditStore(filepath.Join(t.TempDir(), "audit.log")) + if err != nil { + t.Fatal(err) + } + events, err := store.recent(5) + if err != nil { + t.Fatal(err) + } + if len(events) != 0 { + t.Fatalf("expected no events, got %+v", events) + } +} + +func TestAuditStoreAppendWithoutPath(t *testing.T) { + store, err := newAuditStore("") + if err != nil { + t.Fatal(err) + } + if err := store.append(auditEvent{Timestamp: time.Now()}); err != nil { + t.Fatal(err) + } +} diff --git a/cmd/server/install_jobs.go b/cmd/server/install_jobs.go new file mode 100644 index 0000000..6eb27f5 --- /dev/null +++ b/cmd/server/install_jobs.go @@ -0,0 +1,199 @@ +package main + +import ( + "strings" + "sync" + "time" +) + +type installJobStep struct { + At time.Time `json:"at"` + Stage string `json:"stage"` + Message string `json:"message"` +} + +type installJobSnapshot struct { + ID string `json:"id"` + PrinterID string `json:"printer_id"` + Host string `json:"host,omitempty"` + Port int `json:"port,omitempty"` + HostType string `json:"host_type,omitempty"` + Status string `json:"status"` + Stage string `json:"stage"` + Message string `json:"message"` + Steps []installJobStep `json:"steps"` + Output string `json:"output"` + Result *sshInstallResponse `json:"result,omitempty"` + Error string `json:"error,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + CompletedAt *time.Time `json:"completed_at,omitempty"` +} + +type installJob struct { + mu sync.RWMutex + ID string + PrinterID string + Host string + Port int + HostType string + Status string + Stage string + Message string + Steps []installJobStep + Output []string + Result *sshInstallResponse + Error string + CreatedAt time.Time + UpdatedAt time.Time + CompletedAt *time.Time +} + +func (s *server) newInstallJob(req sshInstallRequest) (*installJob, error) { + id, err := newID() + if err != nil { + return nil, err + } + job := &installJob{ + ID: id, + PrinterID: strings.TrimSpace(req.PrinterID), + Host: strings.TrimSpace(req.Host), + Port: req.Port, + HostType: normalizeInstallHostType(req.HostType), + Status: "queued", + Stage: "queued", + Message: "Waiting to start installer job.", + CreatedAt: time.Now().UTC(), + UpdatedAt: time.Now().UTC(), + } + s.installJobsMu.Lock() + s.installJobs[id] = job + s.installJobsMu.Unlock() + return job, nil +} + +func (s *server) getInstallJob(id string) (*installJob, bool) { + s.installJobsMu.RLock() + job, ok := s.installJobs[id] + s.installJobsMu.RUnlock() + return job, ok +} + +func (j *installJob) addStep(stage, message string) { + j.mu.Lock() + defer j.mu.Unlock() + now := time.Now().UTC() + j.Stage = stage + j.Message = message + j.UpdatedAt = now + j.Steps = append(j.Steps, installJobStep{At: now, Stage: stage, Message: message}) + if len(j.Steps) > 120 { + j.Steps = append([]installJobStep(nil), j.Steps[len(j.Steps)-120:]...) + } + if message != "" { + j.Output = append(j.Output, formatInstallJobLine(now, stage, message)) + if len(j.Output) > 240 { + j.Output = append([]string(nil), j.Output[len(j.Output)-240:]...) + } + } +} + +func (j *installJob) markRunning(stage, message string) { + j.mu.Lock() + defer j.mu.Unlock() + now := time.Now().UTC() + j.Status = "running" + j.Stage = stage + j.Message = message + j.UpdatedAt = now + j.Steps = append(j.Steps, installJobStep{At: now, Stage: stage, Message: message}) + if len(j.Steps) > 120 { + j.Steps = append([]installJobStep(nil), j.Steps[len(j.Steps)-120:]...) + } + if message != "" { + j.Output = append(j.Output, formatInstallJobLine(now, stage, message)) + if len(j.Output) > 240 { + j.Output = append([]string(nil), j.Output[len(j.Output)-240:]...) + } + } +} + +func (j *installJob) addOutput(stage, message string) { + j.mu.Lock() + defer j.mu.Unlock() + now := time.Now().UTC() + j.UpdatedAt = now + j.Output = append(j.Output, formatInstallJobLine(now, stage, message)) + if len(j.Output) > 240 { + j.Output = append([]string(nil), j.Output[len(j.Output)-240:]...) + } +} + +func (j *installJob) finish(status, stage, message string, resp *sshInstallResponse, err error) { + j.mu.Lock() + defer j.mu.Unlock() + now := time.Now().UTC() + j.Status = status + j.Stage = stage + j.Message = message + j.UpdatedAt = now + if status == "succeeded" || status == "failed" { + j.CompletedAt = &now + } + if resp != nil { + j.Result = resp + } + if err != nil { + j.Error = err.Error() + } + if message != "" { + j.Output = append(j.Output, formatInstallJobLine(now, stage, message)) + } +} + +func (j *installJob) snapshot() installJobSnapshot { + j.mu.RLock() + defer j.mu.RUnlock() + steps := append([]installJobStep(nil), j.Steps...) + output := strings.Join(j.Output, "\n") + var completedAt *time.Time + if j.CompletedAt != nil { + t := *j.CompletedAt + completedAt = &t + } + var result *sshInstallResponse + if j.Result != nil { + r := *j.Result + result = &r + } + return installJobSnapshot{ + ID: j.ID, + PrinterID: j.PrinterID, + Host: j.Host, + Port: j.Port, + HostType: j.HostType, + Status: j.Status, + Stage: j.Stage, + Message: j.Message, + Steps: steps, + Output: output, + Result: result, + Error: j.Error, + CreatedAt: j.CreatedAt, + UpdatedAt: j.UpdatedAt, + CompletedAt: completedAt, + } +} + +func formatInstallJobLine(at time.Time, stage, message string) string { + ts := at.Format("15:04:05") + stage = strings.TrimSpace(stage) + message = strings.TrimSpace(message) + if stage == "" { + return ts + " " + message + } + if message == "" { + return ts + " [" + stage + "]" + } + return ts + " [" + stage + "] " + message +} diff --git a/cmd/server/live_smoke_test.go b/cmd/server/live_smoke_test.go new file mode 100644 index 0000000..1fe5055 --- /dev/null +++ b/cmd/server/live_smoke_test.go @@ -0,0 +1,545 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/cookiejar" + "net/url" + "os" + "strings" + "testing" + "time" +) + +func TestLiveRealPrinterSmoke(t *testing.T) { + if os.Getenv("KA_RUN_LIVE_SMOKE") == "" { + t.Skip("live printer smoke test is opt-in; set KA_RUN_LIVE_SMOKE=1") + } + baseURL := os.Getenv("KA_LIVE_SMOKE_URL") + if baseURL == "" { + baseURL = "http://127.0.0.1:8080" + } + printerID := os.Getenv("KA_LIVE_PRINTER_ID") + if printerID == "" { + printerID = "F005-02B0" + } + username := os.Getenv("KA_LIVE_ADMIN_USER") + if username == "" { + username = "admin" + } + password := os.Getenv("KA_LIVE_ADMIN_PASSWORD") + if password == "" { + password = "admin" + } + + client := liveSmokeClient(t, baseURL, username, password) + health := liveSmokeGetJSON(t, client, baseURL+"/api/printers/"+url.PathEscape(printerID)+"/health") + if connected, _ := health["connected"].(bool); !connected { + t.Fatalf("printer %s is not connected: %+v", printerID, health) + } + heartbeat, ok := health["health"].(map[string]any) + if !ok { + t.Fatalf("missing heartbeat payload: %+v", health) + } + if reachable, _ := heartbeat["moonraker_reachable"].(bool); !reachable { + t.Fatalf("moonraker is not reachable for %s: %+v", printerID, heartbeat) + } + + session := liveSmokeGetJSON(t, client, baseURL+"/api/session") + if authenticated, _ := session["authenticated"].(bool); !authenticated { + t.Fatalf("session should be authenticated: %+v", session) + } + if isAdmin, _ := session["is_admin"].(bool); !isAdmin { + t.Fatalf("session should be admin for bootstrap account: %+v", session) + } + accountPage := liveSmokeGetText(t, client, baseURL+"/account") + if !strings.Contains(accountPage, "Change password") { + t.Fatalf("/account page missing password form: %s", accountPage) + } + account := liveSmokeGetJSON(t, client, baseURL+"/api/account") + accountUser, ok := account["user"].(map[string]any) + if !ok || accountUser["username"] != username { + t.Fatalf("/api/account returned wrong user: %+v", account) + } + settings := liveSmokeGetJSON(t, client, baseURL+"/api/printers/"+url.PathEscape(printerID)+"/settings") + settingsPayload, ok := settings["settings"].(map[string]any) + if !ok { + t.Fatalf("/api/printers/%s/settings missing settings: %+v", printerID, settings) + } + if synced, state := liveSmokeSettingsSynced(settingsPayload); !synced { + t.Fatalf("/api/printers/%s/settings should be synced, state=%q: %+v", printerID, state, settings) + } + patchPayload := map[string]any{ + "control_mode": settingsPayload["control_mode"], + "ui_url": settingsPayload["ui_url"], + "ui_auto_detect": settingsPayload["ui_auto_detect"], + } + liveSmokePatchJSON(t, client, baseURL, baseURL+"/api/printers/"+url.PathEscape(printerID)+"/settings", patchPayload) + auditPage := liveSmokeGetText(t, client, baseURL+"/audit") + if !strings.Contains(auditPage, "Audit log") { + t.Fatalf("/audit page missing heading: %s", auditPage) + } + audit := liveSmokeGetJSON(t, client, baseURL+"/api/audit?limit=20") + if _, ok := audit["events"].([]any); !ok { + t.Fatalf("/api/audit missing events: %+v", audit) + } + adminPage := liveSmokeGetText(t, client, baseURL+"/admin") + if !strings.Contains(adminPage, "Admin tools") { + t.Fatalf("/admin page missing heading: %s", adminPage) + } + + info := liveSmokeGetJSON(t, client, baseURL+"/p/"+url.PathEscape(printerID)+"/moonraker/printer/info") + result, ok := info["result"].(map[string]any) + if !ok { + t.Fatalf("unexpected printer info payload: %+v", info) + } + if hostname, _ := result["hostname"].(string); hostname == "" { + t.Fatalf("printer info missing hostname: %+v", result) + } + + printStatus := liveSmokeGetJSON(t, client, baseURL+"/p/"+url.PathEscape(printerID)+"/moonraker/printer/objects/query?print_stats&display_status") + statusResult, ok := printStatus["result"].(map[string]any) + if !ok { + t.Fatalf("unexpected print status payload: %+v", printStatus) + } + status, ok := statusResult["status"].(map[string]any) + if !ok { + t.Fatalf("print status missing status map: %+v", statusResult) + } + if printStats, ok := status["print_stats"].(map[string]any); !ok { + t.Fatalf("print status missing print_stats: %+v", status) + } else if state, _ := printStats["state"].(string); state == "" { + t.Fatalf("print_stats missing state: %+v", printStats) + } + + scopedUsername := fmt.Sprintf("viewer-%d", time.Now().UnixNano()) + scopedPassword := "viewer1234" + createPayload := map[string]any{ + "username": scopedUsername, + "password": scopedPassword, + "role": "user", + "printer_grants": []map[string]any{ + {"printer_id": printerID, "access": "read"}, + }, + } + created := liveSmokePostJSON(t, client, baseURL, baseURL+"/api/users", createPayload) + createdUser, ok := created["user"].(map[string]any) + if !ok { + t.Fatalf("create user response missing user payload: %+v", created) + } + scopedUserID, _ := createdUser["id"].(string) + if scopedUserID == "" { + t.Fatalf("create user response missing id: %+v", created) + } + defer func() { + _ = liveSmokeDelete(t, client, baseURL, baseURL+"/api/users/"+url.PathEscape(scopedUserID)) + }() + + scopedClient := liveSmokeClient(t, baseURL, scopedUsername, scopedPassword) + scopedPrinters := liveSmokeGetJSON(t, scopedClient, baseURL+"/api/printers") + printers, _ := scopedPrinters["printers"].([]any) + if len(printers) != 1 { + t.Fatalf("scoped user should only see one printer: %+v", scopedPrinters) + } + if got := liveSmokeGetResponseStatus(t, scopedClient, baseURL+"/api/printers/"+url.PathEscape(printerID)+"/health"); got != http.StatusOK { + t.Fatalf("scoped printer health status = %d", got) + } + if got := liveSmokeGetResponseStatus(t, scopedClient, baseURL+"/api/printers/test/health"); got != http.StatusForbidden { + t.Fatalf("scoped user should be blocked from ungranted printer, got %d", got) + } + + webcams := liveSmokeGetText(t, client, baseURL+"/p/"+url.PathEscape(printerID)+"/moonraker/server/webcams/list") + wantWebcamRoute := "/p/" + url.PathEscape(printerID) + "/camera/Camera/stream" + if !strings.Contains(webcams, wantWebcamRoute) { + t.Fatalf("webcam list missing tunneled stream url %q: %s", wantWebcamRoute, webcams) + } + + detail := liveSmokeGetJSON(t, client, baseURL+"/api/printers/"+url.PathEscape(printerID)) + if statusPayload, ok := detail["print_status"].(map[string]any); !ok || statusPayload == nil { + t.Fatalf("/api/printers/%s missing print_status payload: %+v", printerID, detail) + } else { + if currentLayer, ok := statusPayload["current_layer"]; ok && currentLayer != nil { + if totalLayer, ok := statusPayload["total_layer"]; !ok || totalLayer == nil { + t.Fatalf("/api/printers/%s print_status missing total_layer alongside current_layer: %+v", printerID, statusPayload) + } + } + } + if jobs, ok := detail["recent_jobs"].([]any); !ok || len(jobs) == 0 { + t.Fatalf("/api/printers/%s missing recent_jobs payload: %+v", printerID, detail) + } + detailSettings, ok := detail["settings"].(map[string]any) + if !ok || detailSettings == nil { + t.Fatalf("/api/printers/%s missing settings payload: %+v", printerID, detail) + } + synced, state := liveSmokeSettingsSynced(detailSettings) + if !synced { + t.Fatalf("/api/printers/%s detail should be synced, state=%q: %+v", printerID, state, detail) + } + + if detailHealth, ok := detail["health"].(map[string]any); ok { + if uiReachable, _ := detailHealth["ui_reachable"].(bool); uiReachable { + config := liveSmokeGetJSON(t, client, baseURL+"/printers/"+url.PathEscape(printerID)+"/ui/config.json") + endpoints, ok := config["endpoints"].([]any) + if !ok || len(endpoints) == 0 { + t.Fatalf("ui config missing endpoints: %+v", config) + } + wantEndpoint := baseURL + "/p/" + url.PathEscape(printerID) + "/moonraker" + if got, _ := endpoints[0].(string); got != wantEndpoint { + t.Fatalf("ui config endpoint = %q, want %q", got, wantEndpoint) + } + + uiURL := baseURL + "/printers/" + url.PathEscape(printerID) + "/ui/" + uiResp := liveSmokeGetText(t, client, uiURL) + if strings.Contains(strings.ToLower(uiResp), "welcome to moonraker") { + t.Fatalf("ui route fell back to moonraker for %s: %s", printerID, uiResp[:min(200, len(uiResp))]) + } + + usersPage := liveSmokeGetText(t, client, baseURL+"/users") + if !strings.Contains(usersPage, "Existing users") { + t.Fatalf("/users page missing admin content: %s", usersPage) + } + usersList := liveSmokeGetJSON(t, client, baseURL+"/api/users") + if _, ok := usersList["users"].([]any); !ok { + t.Fatalf("/api/users missing users array: %+v", usersList) + } + + manifestURL := baseURL + "/printers/" + url.PathEscape(printerID) + "/ui/manifest.webmanifest" + manifest := liveSmokeGetResponse(t, client, manifestURL) + if ct := manifest.Header.Get("Content-Type"); !strings.Contains(ct, "application/manifest+json") && !strings.Contains(ct, "application/octet-stream") { + t.Fatalf("manifest content-type = %q", ct) + } + manifestBody := liveSmokeReadBody(t, manifest) + if !strings.Contains(strings.ToLower(manifestBody), `"name":"fluidd"`) { + t.Fatalf("manifest payload looks wrong: %s", manifestBody) + } + + swURL := baseURL + "/printers/" + url.PathEscape(printerID) + "/ui/sw.js" + sw := liveSmokeGetResponse(t, client, swURL) + if ct := sw.Header.Get("Content-Type"); !strings.Contains(ct, "application/javascript") { + t.Fatalf("sw content-type = %q", ct) + } + swBody := liveSmokeReadBody(t, sw) + if !strings.Contains(swBody, "self.registration.unregister") { + t.Fatalf("service worker payload missing unregister logic: %s", swBody) + } + + webcamResp := liveSmokeGetResponse(t, client, baseURL+"/webcam/?action=snapshot") + if webcamResp.StatusCode != http.StatusOK { + t.Fatalf("legacy webcam route status = %d", webcamResp.StatusCode) + } + if ct := webcamResp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "image/jpeg") { + t.Fatalf("legacy webcam content-type = %q", ct) + } + } + } +} + +func TestLiveMockPrinterSmoke(t *testing.T) { + if os.Getenv("KA_RUN_MOCK_SMOKE") == "" { + t.Skip("mock printer smoke test is opt-in; set KA_RUN_MOCK_SMOKE=1") + } + baseURL := os.Getenv("KA_MOCK_SMOKE_URL") + if baseURL == "" { + baseURL = "http://127.0.0.1:8080" + } + printerID := os.Getenv("KA_MOCK_PRINTER_ID") + if printerID == "" { + printerID = "test" + } + username := os.Getenv("KA_MOCK_ADMIN_USER") + if username == "" { + username = "admin" + } + password := os.Getenv("KA_MOCK_ADMIN_PASSWORD") + if password == "" { + password = "admin" + } + + client := liveSmokeClient(t, baseURL, username, password) + health := liveSmokeGetJSON(t, client, baseURL+"/api/printers/"+url.PathEscape(printerID)+"/health") + if connected, _ := health["connected"].(bool); !connected { + t.Fatalf("printer %s is not connected: %+v", printerID, health) + } + heartbeat, ok := health["health"].(map[string]any) + if !ok { + t.Fatalf("missing heartbeat payload: %+v", health) + } + if reachable, _ := heartbeat["moonraker_reachable"].(bool); !reachable { + t.Fatalf("moonraker is not reachable for %s: %+v", printerID, heartbeat) + } + + detail := liveSmokeGetJSON(t, client, baseURL+"/api/printers/"+url.PathEscape(printerID)) + detailHealth, ok := detail["health"].(map[string]any) + if !ok { + t.Fatalf("printer detail missing health: %+v", detail) + } + printStatus, ok := detailHealth["print_status"].(map[string]any) + if !ok { + t.Fatalf("printer detail missing print_status heartbeat: %+v", detailHealth) + } + if currentLayer, _ := printStatus["current_layer"].(float64); currentLayer < 1 { + t.Fatalf("printer detail missing current_layer: %+v", printStatus) + } + if totalLayer, _ := printStatus["total_layer"].(float64); totalLayer < 1 { + t.Fatalf("printer detail missing total_layer: %+v", printStatus) + } + + printStatusResp := liveSmokeGetJSON(t, client, baseURL+"/p/"+url.PathEscape(printerID)+"/moonraker/printer/objects/query?print_stats&display_status&gcode_move&toolhead") + statusResult, ok := printStatusResp["result"].(map[string]any) + if !ok { + t.Fatalf("unexpected print status payload: %+v", printStatusResp) + } + status, ok := statusResult["status"].(map[string]any) + if !ok { + t.Fatalf("print status missing status map: %+v", statusResult) + } + printStats, ok := status["print_stats"].(map[string]any) + if !ok { + t.Fatalf("print status missing print_stats: %+v", status) + } + if _, ok := status["gcode_move"].(map[string]any); !ok { + t.Fatalf("print status missing gcode_move: %+v", status) + } + if _, ok := status["toolhead"].(map[string]any); !ok { + t.Fatalf("print status missing toolhead: %+v", status) + } + info, ok := printStats["info"].(map[string]any) + if !ok { + t.Fatalf("print status missing info: %+v", printStats) + } + if currentLayer, _ := info["current_layer"].(float64); currentLayer != 0 { + t.Fatalf("mock raw current_layer = %v, want 0", currentLayer) + } + if totalLayer, _ := info["total_layer"].(float64); totalLayer != 0 { + t.Fatalf("mock raw total_layer = %v, want 0", totalLayer) + } + if currentLayer, _ := printStatus["current_layer"].(float64); currentLayer < 1 { + t.Fatalf("printer detail missing fallback current_layer: %+v", printStatus) + } + if totalLayer, _ := printStatus["total_layer"].(float64); totalLayer < 1 { + t.Fatalf("printer detail missing fallback total_layer: %+v", printStatus) + } +} + +func liveSmokeClient(t *testing.T, baseURL, username, password string) *http.Client { + t.Helper() + + jar, err := cookiejar.New(nil) + if err != nil { + t.Fatal(err) + } + client := &http.Client{ + Jar: jar, + Timeout: 20 * time.Second, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + }, + } + + liveSmokeGetText(t, client, baseURL+"/login") + form := url.Values{} + form.Set("username", username) + form.Set("password", password) + + resp, err := client.PostForm(baseURL+"/login", form) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusSeeOther { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("login status = %d, want 303; body=%s", resp.StatusCode, string(body)) + } + + return client +} + +func liveSmokeGetJSON(t *testing.T, client *http.Client, rawURL string) map[string]any { + t.Helper() + body := liveSmokeGetText(t, client, rawURL) + var payload map[string]any + if err := json.Unmarshal([]byte(body), &payload); err != nil { + t.Fatalf("failed to parse json from %s: %v\nbody=%s", rawURL, err, body) + } + return payload +} + +func liveSmokeGetText(t *testing.T, client *http.Client, rawURL string) string { + t.Helper() + + resp := liveSmokeGetResponse(t, client, rawURL) + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + if resp.StatusCode >= 500 { + t.Fatalf("GET %s returned %d: %s", rawURL, resp.StatusCode, string(body)) + } + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusSeeOther { + return fmt.Sprintf("%s", body) + } + return string(body) +} + +func liveSmokeGetResponse(t *testing.T, client *http.Client, rawURL string) *http.Response { + t.Helper() + + resp, err := client.Get(rawURL) + if err != nil { + t.Fatal(err) + } + if resp.StatusCode >= 500 { + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + t.Fatalf("GET %s returned %d: %s", rawURL, resp.StatusCode, string(body)) + } + return resp +} + +func liveSmokeGetResponseStatus(t *testing.T, client *http.Client, rawURL string) int { + t.Helper() + resp, err := client.Get(rawURL) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + return resp.StatusCode +} + +func liveSmokePostJSON(t *testing.T, client *http.Client, baseURL string, rawURL string, payload any) map[string]any { + t.Helper() + body, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + req, err := http.NewRequest(http.MethodPost, rawURL, bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-CSRF-Token", liveSmokeCSRFToken(t, client, baseURL)) + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode >= 400 { + b, _ := io.ReadAll(resp.Body) + t.Fatalf("POST %s returned %d: %s", rawURL, resp.StatusCode, string(b)) + } + var out map[string]any + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + t.Fatalf("failed to decode response from %s: %v", rawURL, err) + } + return out +} + +func liveSmokePatchJSON(t *testing.T, client *http.Client, baseURL string, rawURL string, payload any) map[string]any { + t.Helper() + body, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + req, err := http.NewRequest(http.MethodPatch, rawURL, bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-CSRF-Token", liveSmokeCSRFToken(t, client, baseURL)) + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode >= 400 { + b, _ := io.ReadAll(resp.Body) + t.Fatalf("PATCH %s returned %d: %s", rawURL, resp.StatusCode, string(b)) + } + var out map[string]any + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + t.Fatalf("failed to decode response from %s: %v", rawURL, err) + } + return out +} + +func liveSmokeDelete(t *testing.T, client *http.Client, baseURL string, rawURL string) error { + t.Helper() + req, err := http.NewRequest(http.MethodDelete, rawURL, nil) + if err != nil { + return err + } + req.Header.Set("X-CSRF-Token", liveSmokeCSRFToken(t, client, baseURL)) + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode >= 400 { + b, _ := io.ReadAll(resp.Body) + return fmt.Errorf("delete failed: %d %s", resp.StatusCode, string(b)) + } + return nil +} + +func liveSmokeCSRFToken(t *testing.T, client *http.Client, baseURL string) string { + t.Helper() + resp, err := client.Get(baseURL + "/api/session") + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var session map[string]any + if err := json.NewDecoder(resp.Body).Decode(&session); err != nil { + t.Fatal(err) + } + token, _ := session["csrf_token"].(string) + if token == "" { + t.Fatal("missing csrf token") + } + return token +} + +func liveSmokeReadBody(t *testing.T, resp *http.Response) string { + t.Helper() + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + return string(body) +} + +func liveSmokeSettingsSynced(settings map[string]any) (bool, string) { + updatedAt := liveSmokeParseTimestamp(settings["updated_at"]) + lastSyncedAt := liveSmokeParseTimestamp(settings["last_synced_at"]) + if updatedAt > 0 && lastSyncedAt >= updatedAt { + return true, "Synced" + } + return false, "Pending" +} + +func liveSmokeParseTimestamp(value any) int64 { + s, _ := value.(string) + if s == "" { + return 0 + } + ts, err := time.Parse(time.RFC3339Nano, s) + if err != nil { + ts, err = time.Parse(time.RFC3339, s) + if err != nil { + return 0 + } + } + return ts.UnixNano() +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..ae76a9a --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,3560 @@ +package main + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "encoding/json" + "flag" + "fmt" + "io" + "log" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "sync" + "time" + + "github.com/gorilla/websocket" + "github.com/klipperanywhere/klipperanywhere/internal/protocol" +) + +var serverVersion = "dev" + +type tunnel struct { + printerID string + remoteAddr string + connectedAt time.Time + conn *websocket.Conn + writeMu sync.Mutex + pending map[string]chan protocol.Message + pendingMu sync.Mutex + health *protocol.Health + healthMu sync.RWMutex + done chan struct{} +} + +type server struct { + agentToken string + cookieSecure bool + controlMode string + upgrader websocket.Upgrader + tunnels map[string]*tunnel + tunnelsMu sync.RWMutex + users *userStore + auditLog *auditStore + printerSettings *printerSettingsStore + notificationSettings *notificationSettingsStore + notifier *telegramNotifier + installJobs map[string]*installJob + installJobsMu sync.RWMutex + sessions map[string]sessionRecord + sessionsMu sync.RWMutex + loginLimiter *loginLimiter +} + +type sessionRecord struct { + UserID string + CSRFToken string + ExpiresAt time.Time +} + +type authenticatedSession struct { + UserID string + Username string + Role string + PrinterGrants []printerGrant + CSRFToken string + ExpiresAt time.Time +} + +type loginAttempt struct { + Count int + WindowEnds time.Time +} + +type loginLimiter struct { + mu sync.Mutex + attempts map[string]loginAttempt + limit int + window time.Duration +} + +func main() { + var listen string + var token string + var adminUser string + var adminPass string + var usersFile string + var auditFile string + var settingsFile string + var notificationSettingsFile string + var cookieSecure bool + var controlMode string + + flag.StringVar(&listen, "listen", ":8080", "address to listen on") + flag.StringVar(&token, "agent-token", envOrDefault("KA_AGENT_TOKEN", "dev-token"), "shared agent token for local development") + flag.StringVar(&adminUser, "admin-user", envOrDefault("KA_ADMIN_USER", "admin"), "admin username") + flag.StringVar(&adminPass, "admin-password", envOrDefault("KA_ADMIN_PASSWORD", "admin"), "admin password") + flag.StringVar(&usersFile, "users-file", envOrDefault("KA_USERS_FILE", "data/users.json"), "path to the persistent users file") + flag.StringVar(&auditFile, "audit-file", envOrDefault("KA_AUDIT_FILE", "data/audit.log"), "path to the append-only audit log") + flag.StringVar(&settingsFile, "settings-file", envOrDefault("KA_PRINTER_SETTINGS_FILE", "data/printer-settings.json"), "path to synced printer settings") + flag.StringVar(¬ificationSettingsFile, "notification-settings-file", envOrDefault("KA_NOTIFICATION_SETTINGS_FILE", "data/notification-settings.json"), "path to global notification settings") + flag.BoolVar(&cookieSecure, "cookie-secure", false, "set Secure on session cookies") + flag.StringVar(&controlMode, "control-mode", envOrDefault("KA_CONTROL_MODE", "readonly"), "printer control mode: readonly or full") + flag.Parse() + if envBool("KA_COOKIE_SECURE") { + cookieSecure = true + } + warnIfDevelopmentSecrets(token, adminUser, adminPass, cookieSecure) + rawControlMode := controlMode + controlMode = normalizeControlMode(controlMode) + if controlMode == "" { + log.Printf("WARNING: invalid control mode %q; falling back to readonly", rawControlMode) + controlMode = "readonly" + } + users, err := newUserStore(usersFile, adminUser, adminPass) + if err != nil { + log.Fatal(err) + } + audit, err := newAuditStore(auditFile) + if err != nil { + log.Fatal(err) + } + printerSettings, err := newPrinterSettingsStore(settingsFile) + if err != nil { + log.Fatal(err) + } + notificationSettings, err := newNotificationSettingsStore(notificationSettingsFile) + if err != nil { + log.Fatal(err) + } + + s := &server{ + agentToken: token, + cookieSecure: cookieSecure, + controlMode: controlMode, + upgrader: websocket.Upgrader{ + CheckOrigin: func(r *http.Request) bool { + return true + }, + }, + tunnels: make(map[string]*tunnel), + users: users, + auditLog: audit, + printerSettings: printerSettings, + notificationSettings: notificationSettings, + notifier: &telegramNotifier{client: &http.Client{Timeout: 15 * time.Second}, settings: notificationSettings}, + installJobs: make(map[string]*installJob), + sessions: make(map[string]sessionRecord), + loginLimiter: newLoginLimiter(5, 5*time.Minute), + } + go (&telegramBot{ + client: &http.Client{Timeout: 30 * time.Second}, + settings: notificationSettings, + server: s, + }).run(context.Background()) + + mux := http.NewServeMux() + mux.HandleFunc("/agent/tunnel", s.handleAgentTunnel) + mux.HandleFunc("/p/", s.requireAuth(s.handlePrinterProxy)) + mux.HandleFunc("/webcam/", s.requireAuth(s.handleLegacyWebcamProxy)) + mux.HandleFunc("/api/session", s.handleSessionAPI) + mux.HandleFunc("/api/printers", s.requireAuth(s.handlePrintersAPI)) + mux.HandleFunc("/api/printers/", s.requireAuth(s.handlePrinterAPI)) + mux.HandleFunc("/dashboard", s.requireAuth(s.handleDashboard)) + mux.HandleFunc("/account", s.requireAuth(s.handleAccountPage)) + mux.HandleFunc("/api/account", s.requireAuth(s.handleAccountAPI)) + mux.HandleFunc("/admin", s.requireAdmin(s.handleAdminPage)) + mux.HandleFunc("/api/notifications", s.requireAdmin(s.handleNotificationsAPI)) + mux.HandleFunc("/api/notifications/test", s.requireAdmin(s.handleNotificationsTestAPI)) + mux.HandleFunc("/install", s.requireAdmin(s.handleInstallPage)) + mux.HandleFunc("/api/install/ssh", s.requireAdmin(s.handleInstallSSHAPI)) + mux.HandleFunc("/api/install/ssh/jobs/", s.requireAdmin(s.handleInstallSSHJobAPI)) + mux.HandleFunc("/audit", s.requireAdmin(s.handleAuditPage)) + mux.HandleFunc("/api/audit", s.requireAdmin(s.handleAuditAPI)) + mux.HandleFunc("/users", s.requireAdmin(s.handleUsersPage)) + mux.HandleFunc("/api/users", s.requireAdmin(s.handleUsersAPI)) + mux.HandleFunc("/api/users/", s.requireAdmin(s.handleUserAPI)) + mux.HandleFunc("/printers/", s.requireAuth(s.handlePrinterPage)) + mux.HandleFunc("/login", s.handleLogin) + mux.HandleFunc("/logout", s.handleLogout) + mux.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, "web/static/assets/favicon.png") + }) + mux.HandleFunc("/apple-touch-icon.png", func(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, "web/static/assets/favicon.png") + }) + mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static")))) + mux.HandleFunc("/", s.handleLandingPage) + mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok\n")) + }) + + log.Printf("server listening on %s", listen) + if err := http.ListenAndServe(listen, mux); err != nil { + log.Fatal(err) + } +} + +func (s *server) requireAuth(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if isPublicPrinterUIAsset(r.URL.Path) { + next(w, r) + return + } + if s.isAuthenticated(r) { + next(w, r) + return + } + if strings.HasPrefix(r.URL.Path, "/api/") { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) + return + } + http.Redirect(w, r, "/login", http.StatusSeeOther) + } +} + +func isPublicPrinterUIAsset(path string) bool { + return strings.HasSuffix(path, "/manifest.webmanifest") || strings.HasSuffix(path, "/sw.js") +} + +func (s *server) isAuthenticated(r *http.Request) bool { + _, ok := s.currentSession(r) + return ok +} + +func (s *server) currentSession(r *http.Request) (authenticatedSession, bool) { + cookie, err := r.Cookie("ka_session") + if err != nil || cookie.Value == "" { + return authenticatedSession{}, false + } + + s.sessionsMu.RLock() + sess, ok := s.sessions[cookie.Value] + s.sessionsMu.RUnlock() + if !ok || time.Now().After(sess.ExpiresAt) { + if ok { + s.sessionsMu.Lock() + delete(s.sessions, cookie.Value) + s.sessionsMu.Unlock() + } + return authenticatedSession{}, false + } + user, ok := s.users.getByID(sess.UserID) + if !ok { + s.sessionsMu.Lock() + delete(s.sessions, cookie.Value) + s.sessionsMu.Unlock() + return authenticatedSession{}, false + } + return authenticatedSession{ + UserID: user.ID, + Username: user.Username, + Role: user.Role, + PrinterGrants: append([]printerGrant(nil), user.PrinterGrants...), + CSRFToken: sess.CSRFToken, + ExpiresAt: sess.ExpiresAt, + }, true +} + +func (s *server) handleLandingPage(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + http.ServeFile(w, r, "web/static/index.html") +} + +func (s *server) handleDashboard(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/dashboard" { + http.NotFound(w, r) + return + } + sess, ok := s.currentSession(r) + if !ok { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + page, err := os.ReadFile("web/static/dashboard.html") + if err != nil { + http.Error(w, "dashboard unavailable", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _, _ = w.Write([]byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken))) +} + +func (s *server) handleAccountPage(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/account" { + http.NotFound(w, r) + return + } + sess, ok := s.currentSession(r) + if !ok { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + page, err := os.ReadFile("web/static/account.html") + if err != nil { + http.Error(w, "account page unavailable", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + page = []byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken)) + page = []byte(strings.ReplaceAll(string(page), "{{USERNAME}}", sess.Username)) + page = []byte(strings.ReplaceAll(string(page), "{{ROLE}}", sess.Role)) + _, _ = w.Write(page) +} + +func (s *server) handleAdminPage(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/admin" { + http.NotFound(w, r) + return + } + sess, ok := s.currentSession(r) + if !ok { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + page, err := os.ReadFile("web/static/admin.html") + if err != nil { + http.Error(w, "admin page unavailable", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + page = []byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken)) + _, _ = w.Write(page) +} + +func (s *server) handleAccountAPI(w http.ResponseWriter, r *http.Request) { + sess, ok := s.currentSession(r) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) + return + } + switch r.Method { + case http.MethodGet: + user, ok := s.users.getByID(sess.UserID) + if !ok { + writeJSON(w, http.StatusNotFound, map[string]any{"error": "user not found"}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"user": user}) + case http.MethodPatch: + if !s.verifyCSRF(w, r, sess) { + return + } + var body struct { + CurrentPassword string `json:"current_password"` + NewPassword string `json:"new_password"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + if strings.TrimSpace(body.CurrentPassword) == "" || strings.TrimSpace(body.NewPassword) == "" { + http.Error(w, "current password and new password are required", http.StatusBadRequest) + return + } + if err := s.users.changePassword(sess.UserID, body.CurrentPassword, body.NewPassword); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("account_password_change"), + Detail: "changed own password", + }) + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) + default: + w.Header().Set("Allow", "GET, PATCH") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func (s *server) handleNotificationsAPI(w http.ResponseWriter, r *http.Request) { + sess, ok := s.currentSession(r) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) + return + } + if sess.Role != "admin" { + http.Error(w, "admin access required", http.StatusForbidden) + return + } + switch r.Method { + case http.MethodGet: + if s.notificationSettings == nil { + writeJSON(w, http.StatusOK, map[string]any{"notifications": publicNotificationSettings(notificationSettingsRecord{})}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"notifications": publicNotificationSettings(s.notificationSettings.snapshot())}) + case http.MethodPatch: + if !s.verifyCSRF(w, r, sess) { + return + } + if s.notificationSettings == nil { + http.Error(w, "notification settings are unavailable", http.StatusInternalServerError) + return + } + before := s.notificationSettings.snapshot() + var body struct { + TelegramEnabled *bool `json:"telegram_enabled"` + TelegramCommandsEnabled *bool `json:"telegram_commands_enabled"` + TelegramBotToken *string `json:"telegram_bot_token"` + TelegramChatID *string `json:"telegram_chat_id"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + updated, err := s.notificationSettings.update(body.TelegramEnabled, body.TelegramCommandsEnabled, body.TelegramBotToken, body.TelegramChatID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("notification_settings_update"), + Detail: describeNotificationSettingsChange(before, updated), + }) + writeJSON(w, http.StatusOK, map[string]any{ + "ok": true, + "notifications": publicNotificationSettings(updated), + }) + default: + w.Header().Set("Allow", "GET, PATCH") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func (s *server) handleNotificationsTestAPI(w http.ResponseWriter, r *http.Request) { + sess, ok := s.currentSession(r) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) + return + } + if sess.Role != "admin" { + http.Error(w, "admin access required", http.StatusForbidden) + return + } + if r.Method != http.MethodPost { + w.Header().Set("Allow", "POST") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + if !s.verifyCSRF(w, r, sess) { + return + } + if s.notificationSettings == nil || s.notifier == nil { + http.Error(w, "notification settings are unavailable", http.StatusInternalServerError) + return + } + var body struct { + TelegramEnabled *bool `json:"telegram_enabled"` + TelegramBotToken *string `json:"telegram_bot_token"` + TelegramChatID *string `json:"telegram_chat_id"` + Message *string `json:"message"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil && err != io.EOF { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + record := s.notificationSettings.snapshot() + if body.TelegramEnabled != nil { + record.TelegramEnabled = *body.TelegramEnabled + } + if body.TelegramBotToken != nil { + record.TelegramBotToken = strings.TrimSpace(*body.TelegramBotToken) + } + if body.TelegramChatID != nil { + record.TelegramChatID = strings.TrimSpace(*body.TelegramChatID) + } + token := strings.TrimSpace(record.TelegramBotToken) + chatID := strings.TrimSpace(record.TelegramChatID) + if token == "" || chatID == "" { + http.Error(w, "telegram bot token and chat ID are required", http.StatusBadRequest) + return + } + message := "" + if body.Message != nil { + message = strings.TrimSpace(*body.Message) + } + if message == "" { + message = "KlipperAnywhere test notification\nIf you received this, Telegram delivery is working." + } + if err := s.notifier.sendTelegramMessage(r.Context(), token, chatID, message); err != nil { + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("notification_settings_test"), + Detail: fmt.Sprintf("failed telegram test notification: %v", err), + }) + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + detail := "sent telegram test notification" + if !record.TelegramEnabled { + detail += " while delivery is disabled" + } + if body.TelegramEnabled != nil || body.TelegramBotToken != nil || body.TelegramChatID != nil { + detail += " using submitted values" + } else { + detail += " using saved settings" + } + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("notification_settings_test"), + Detail: detail, + }) + responseMessage := "Test notification sent." + if !record.TelegramEnabled { + responseMessage = "Test notification sent while Telegram delivery is disabled." + } + writeJSON(w, http.StatusOK, map[string]any{ + "ok": true, + "message": responseMessage, + }) +} + +func (s *server) requireAdmin(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + sess, ok := s.currentSession(r) + if !ok { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + if sess.Role != "admin" { + http.Error(w, "admin access required", http.StatusForbidden) + return + } + next(w, r) + } +} + +func (s *server) authorizePrinter(w http.ResponseWriter, r *http.Request, printerID string, control bool) (authenticatedSession, bool) { + sess, ok := s.currentSession(r) + if !ok { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return authenticatedSession{}, false + } + if sess.Role != "admin" && !s.users.canAccessPrinter(sess.UserID, printerID, control) { + http.Error(w, "printer access denied", http.StatusForbidden) + return authenticatedSession{}, false + } + return sess, true +} + +func (s *server) filteredConnectedPrinters(userID string) []string { + s.tunnelsMu.RLock() + printerIDs := make([]string, 0, len(s.tunnels)) + for printerID := range s.tunnels { + printerIDs = append(printerIDs, printerID) + } + s.tunnelsMu.RUnlock() + return s.users.visiblePrinters(userID, printerIDs) +} + +func (s *server) handlePrinterPage(w http.ResponseWriter, r *http.Request) { + if strings.TrimPrefix(r.URL.Path, "/printers/") == "" { + http.NotFound(w, r) + return + } + if printerID, ok := parsePrinterAgentPath(r.URL.Path); ok { + if _, ok := s.authorizePrinter(w, r, printerID, false); !ok { + return + } + http.ServeFile(w, r, "web/static/printer-agent.html") + return + } + if printerID, ok := parsePrinterSettingsPath(r.URL.Path); ok { + if _, ok := s.authorizePrinter(w, r, printerID, false); !ok { + return + } + http.ServeFile(w, r, "web/static/printer-settings.html") + return + } + if printerID, uiPath, ok := parsePrinterUIPath(r.URL.Path); ok { + if uiPath == "/manifest.webmanifest" || uiPath == "/sw.js" { + s.handleUIProxy(w, r, printerID, uiPath, "") + return + } + sess, ok := s.authorizePrinter(w, r, printerID, false) + if !ok { + return + } + s.handleUIProxy(w, r, printerID, uiPath, sess.Username) + return + } + if printerID, ok := parsePrinterRootPath(r.URL.Path); ok { + if _, ok := s.authorizePrinter(w, r, printerID, false); !ok { + return + } + } + http.ServeFile(w, r, "web/static/printer.html") +} + +func (s *server) handleLogin(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + if s.isAuthenticated(r) { + http.Redirect(w, r, "/dashboard", http.StatusSeeOther) + return + } + http.ServeFile(w, r, "web/static/login.html") + case http.MethodPost: + clientIP := requestIP(r) + if !s.loginLimiter.allow(clientIP) { + http.Error(w, "too many login attempts", http.StatusTooManyRequests) + return + } + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid form", http.StatusBadRequest) + return + } + username := r.FormValue("username") + password := r.FormValue("password") + user, ok, err := s.users.authenticate(username, password) + if err != nil { + http.Error(w, "authentication unavailable", http.StatusInternalServerError) + return + } + if !ok { + http.Redirect(w, r, "/login?error=1", http.StatusSeeOther) + return + } + s.loginLimiter.reset(clientIP) + + sessionID, err := newID() + if err != nil { + http.Error(w, "failed to create session", http.StatusInternalServerError) + return + } + csrfToken, err := newID() + if err != nil { + http.Error(w, "failed to create session", http.StatusInternalServerError) + return + } + expiresAt := time.Now().Add(12 * time.Hour) + s.sessionsMu.Lock() + s.sessions[sessionID] = sessionRecord{ + UserID: user.ID, + CSRFToken: csrfToken, + ExpiresAt: expiresAt, + } + s.sessionsMu.Unlock() + + http.SetCookie(w, &http.Cookie{ + Name: "ka_session", + Value: sessionID, + Path: "/", + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: s.cookieSecure, + Expires: expiresAt, + }) + s.logAudit(auditEvent{ + Actor: user.Username, + Action: actionLabel("login"), + Detail: "successful login", + }) + http.Redirect(w, r, "/dashboard", http.StatusSeeOther) + default: + w.Header().Set("Allow", "GET, POST") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func (s *server) handleLogout(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.Header().Set("Allow", "POST") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + sess, ok := s.currentSession(r) + if !ok { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid form", http.StatusBadRequest) + return + } + if !constantTimeEqual(r.FormValue("csrf_token"), sess.CSRFToken) { + http.Error(w, "invalid csrf token", http.StatusForbidden) + return + } + if cookie, err := r.Cookie("ka_session"); err == nil { + s.sessionsMu.Lock() + delete(s.sessions, cookie.Value) + s.sessionsMu.Unlock() + } + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("logout"), + Detail: "signed out", + }) + http.SetCookie(w, &http.Cookie{ + Name: "ka_session", + Value: "", + Path: "/", + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: s.cookieSecure, + MaxAge: -1, + }) + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (s *server) handleSessionAPI(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.Header().Set("Allow", "GET") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + sess, ok := s.currentSession(r) + if !ok { + writeJSON(w, http.StatusOK, map[string]any{ + "authenticated": false, + }) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "authenticated": true, + "user_id": sess.UserID, + "username": sess.Username, + "role": sess.Role, + "is_admin": sess.Role == "admin", + "printer_grants": sess.PrinterGrants, + "csrf_token": sess.CSRFToken, + "server_version": serverVersion, + }) +} + +func (s *server) handleUsersPage(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/users" { + http.NotFound(w, r) + return + } + page, err := os.ReadFile("web/static/users.html") + if err != nil { + http.Error(w, "users page unavailable", http.StatusInternalServerError) + return + } + sess, ok := s.currentSession(r) + if !ok { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + page = []byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken)) + page = []byte(strings.ReplaceAll(string(page), "{{CURRENT_ROLE}}", sess.Role)) + _, _ = w.Write(page) +} + +func (s *server) handleAuditPage(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/audit" { + http.NotFound(w, r) + return + } + sess, ok := s.currentSession(r) + if !ok { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + page, err := os.ReadFile("web/static/audit.html") + if err != nil { + http.Error(w, "audit page unavailable", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + page = []byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken)) + _, _ = w.Write(page) +} + +func (s *server) handleAuditAPI(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.Header().Set("Allow", "GET") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + sess, ok := s.currentSession(r) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) + return + } + limit := 100 + if raw := strings.TrimSpace(r.URL.Query().Get("limit")); raw != "" { + if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 && parsed <= 500 { + limit = parsed + } + } + events, err := s.auditLog.recent(limit) + if err != nil { + http.Error(w, "unable to load audit events", http.StatusInternalServerError) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "events": events, + "user": sess.Username, + }) +} + +func (s *server) handleUsersAPI(w http.ResponseWriter, r *http.Request) { + sess, ok := s.currentSession(r) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) + return + } + if sess.Role != "admin" { + http.Error(w, "admin access required", http.StatusForbidden) + return + } + switch r.Method { + case http.MethodGet: + users := s.users.listPublic() + writeJSON(w, http.StatusOK, map[string]any{"users": users}) + case http.MethodPost: + if !s.verifyCSRF(w, r, sess) { + return + } + var body struct { + Username string `json:"username"` + Password string `json:"password"` + Role string `json:"role"` + PrinterGrants []printerGrant `json:"printer_grants"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + user, err := s.users.create(body.Username, body.Password, body.Role, body.PrinterGrants) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("user_create"), + TargetID: user.ID, + Detail: "created user " + user.Username, + }) + writeJSON(w, http.StatusCreated, map[string]any{"user": user}) + default: + w.Header().Set("Allow", "GET, POST") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func (s *server) handleUserAPI(w http.ResponseWriter, r *http.Request) { + sess, ok := s.currentSession(r) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) + return + } + if sess.Role != "admin" { + http.Error(w, "admin access required", http.StatusForbidden) + return + } + userID := strings.TrimPrefix(r.URL.Path, "/api/users/") + if userID == "" || strings.Contains(userID, "/") { + http.NotFound(w, r) + return + } + switch r.Method { + case http.MethodPatch: + if !s.verifyCSRF(w, r, sess) { + return + } + var body struct { + Password string `json:"password"` + Role string `json:"role"` + PrinterGrants []printerGrant `json:"printer_grants"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + updated, err := s.users.update(userID, body.Password, body.Role, body.PrinterGrants) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("user_update"), + TargetID: userID, + Detail: "updated user " + updated.Username, + }) + writeJSON(w, http.StatusOK, map[string]any{"user": updated}) + case http.MethodDelete: + if !s.verifyCSRF(w, r, sess) { + return + } + if err := s.users.delete(userID, sess.UserID); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("user_delete"), + TargetID: userID, + Detail: "deleted user", + }) + w.WriteHeader(http.StatusNoContent) + default: + w.Header().Set("Allow", "PATCH, DELETE") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func (s *server) verifyCSRF(w http.ResponseWriter, r *http.Request, sess authenticatedSession) bool { + if constantTimeEqual(r.Header.Get("X-CSRF-Token"), sess.CSRFToken) { + return true + } + if err := r.ParseForm(); err == nil && constantTimeEqual(r.FormValue("csrf_token"), sess.CSRFToken) { + return true + } + http.Error(w, "invalid csrf token", http.StatusForbidden) + return false +} + +func (s *server) handleAgentTunnel(w http.ResponseWriter, r *http.Request) { + printerID := r.URL.Query().Get("printer_id") + token := r.URL.Query().Get("token") + if printerID == "" || token == "" { + http.Error(w, "printer_id and token are required", http.StatusBadRequest) + return + } + if token != s.agentToken { + http.Error(w, "invalid token", http.StatusUnauthorized) + return + } + + s.tunnelsMu.RLock() + old := s.tunnels[printerID] + if old != nil && old.acceptsDuplicateBlock(time.Now()) { + log.Printf("rejecting duplicate agent tunnel printer_id=%s existing_remote=%s new_remote=%s", printerID, old.remoteAddr, r.RemoteAddr) + s.tunnelsMu.RUnlock() + http.Error(w, "printer agent is already connected", http.StatusConflict) + return + } + s.tunnelsMu.RUnlock() + + conn, err := s.upgrader.Upgrade(w, r, nil) + if err != nil { + log.Printf("upgrade failed: %v", err) + return + } + + t := &tunnel{ + printerID: printerID, + remoteAddr: r.RemoteAddr, + connectedAt: time.Now().UTC(), + conn: conn, + pending: make(map[string]chan protocol.Message), + done: make(chan struct{}), + } + + s.tunnelsMu.Lock() + if old := s.tunnels[printerID]; old != nil { + log.Printf("replacing existing agent tunnel printer_id=%s old_remote=%s new_remote=%s", printerID, old.remoteAddr, r.RemoteAddr) + old.close() + } + s.tunnels[printerID] = t + s.tunnelsMu.Unlock() + + log.Printf("agent connected printer_id=%s remote=%s", printerID, r.RemoteAddr) + go t.readLoop(s) + if err := s.syncPrinterSettings(printerID); err != nil { + log.Printf("failed to sync printer settings printer_id=%s: %v", printerID, err) + } + <-t.done + + s.tunnelsMu.Lock() + if s.tunnels[printerID] == t { + delete(s.tunnels, printerID) + } + s.tunnelsMu.Unlock() + + t.close() + log.Printf("agent disconnected printer_id=%s", printerID) +} + +func (s *server) handlePrintersAPI(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/printers" { + http.NotFound(w, r) + return + } + + sess, ok := s.currentSession(r) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) + return + } + s.tunnelsMu.RLock() + printers := make([]map[string]any, 0, len(s.tunnels)) + for printerID, t := range s.tunnels { + if sess.Role != "admin" && !s.users.canAccessPrinter(sess.UserID, printerID, false) { + continue + } + t.healthMu.RLock() + health := t.health + t.healthMu.RUnlock() + settings := s.printerSettings.current(printerID, health, s.controlMode) + printers = append(printers, map[string]any{ + "printer_id": printerID, + "connected": true, + "health": health, + "settings": settings, + }) + } + s.tunnelsMu.RUnlock() + + writeJSON(w, http.StatusOK, map[string]any{"printers": printers}) +} + +func (s *server) handlePrinterAPI(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/agent/update") { + printerID := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/api/printers/"), "/agent/update") + printerID = strings.Trim(printerID, "/") + if printerID == "" || strings.Contains(printerID, "/") { + http.NotFound(w, r) + return + } + s.handlePrinterAgentUpdateAPI(w, r, printerID) + return + } + printerID, action, ok := parsePrinterAPIPath(r.URL.Path) + if !ok { + http.NotFound(w, r) + return + } + if action == "" { + s.handlePrinterDetailAPI(w, r, printerID) + return + } + switch action { + case "health": + sess, ok := s.authorizePrinter(w, r, printerID, false) + if !ok { + return + } + + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + if t == nil { + writeJSON(w, http.StatusOK, map[string]any{ + "printer_id": printerID, + "connected": false, + }) + return + } + + t.healthMu.RLock() + health := t.health + t.healthMu.RUnlock() + + writeJSON(w, http.StatusOK, map[string]any{ + "printer_id": printerID, + "connected": true, + "health": health, + "user": sess.Username, + }) + case "settings": + s.handlePrinterSettingsAPI(w, r, printerID) + case "agent": + http.NotFound(w, r) + default: + http.NotFound(w, r) + return + } +} + +func (s *server) handlePrinterDetailAPI(w http.ResponseWriter, r *http.Request, printerID string) { + if r.Method != http.MethodGet { + w.Header().Set("Allow", "GET") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + sess, ok := s.authorizePrinter(w, r, printerID, false) + if !ok { + return + } + + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + if t == nil { + synced, state, detail := s.printerSettingsSyncStatus(printerID, nil) + record := s.printerSettings.current(printerID, nil, s.controlMode) + writeJSON(w, http.StatusOK, map[string]any{ + "printer_id": printerID, + "connected": false, + "health": nil, + "info": nil, + "print_status": nil, + "recent_jobs": nil, + "control_mode": s.controlModeForPrinter(printerID, nil), + "settings": s.publicPrinterSettings(record), + "settings_synced": synced, + "settings_sync_state": state, + "settings_sync_detail": detail, + }) + return + } + + t.healthMu.RLock() + health := t.health + t.healthMu.RUnlock() + synced, state, detail := s.printerSettingsSyncStatus(printerID, health) + + info, infoErr := s.fetchPrinterInfo(r.Context(), t) + printStatus, printStatusErr := s.fetchPrinterPrintStatus(r.Context(), t) + recentJobs, recentJobsErr := s.fetchPrinterJobHistory(r.Context(), t) + if printStatus == nil && health != nil { + printStatus = printStatusFromHealth(health) + } + response := map[string]any{ + "printer_id": printerID, + "connected": true, + "health": health, + "info": info, + "print_status": printStatus, + "recent_jobs": recentJobs, + "control_mode": s.controlModeForPrinter(printerID, health), + "access": s.users.printerAccessLevel(sess.UserID, printerID), + "settings": s.publicPrinterSettings(s.printerSettings.current(printerID, health, s.controlMode)), + "settings_synced": synced, + "settings_sync_state": state, + "settings_sync_detail": detail, + } + if infoErr != nil { + response["info_error"] = infoErr.Error() + } + if printStatusErr != nil { + response["print_status_error"] = printStatusErr.Error() + } + if recentJobsErr != nil { + response["recent_jobs_error"] = recentJobsErr.Error() + } + writeJSON(w, http.StatusOK, response) +} + +func (s *server) fetchPrinterInfo(ctx context.Context, t *tunnel) (map[string]any, error) { + id, err := newID() + if err != nil { + return nil, err + } + requestCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + resp, err := t.request(requestCtx, protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Method: http.MethodGet, + Path: "/printer/info", + }) + if err != nil { + return nil, err + } + if resp.Type == protocol.MessageError { + return nil, fmt.Errorf("%s", resp.Error) + } + body, err := base64.StdEncoding.DecodeString(resp.Body) + if err != nil { + return nil, err + } + var parsed struct { + Result map[string]any `json:"result"` + } + if err := json.Unmarshal(body, &parsed); err != nil { + return nil, err + } + return parsed.Result, nil +} + +func (s *server) fetchPrinterPrintStatus(ctx context.Context, t *tunnel) (map[string]any, error) { + return s.fetchPrinterObjectStatus(ctx, t, []string{"print_stats", "display_status"}) +} + +func (s *server) fetchPrinterObjectStatus(ctx context.Context, t *tunnel, objects []string) (map[string]any, error) { + if t == nil { + return nil, fmt.Errorf("printer is not connected") + } + id, err := newID() + if err != nil { + return nil, err + } + requestCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + escaped := make([]string, 0, len(objects)) + for _, object := range objects { + object = strings.TrimSpace(object) + if object == "" { + continue + } + escaped = append(escaped, url.QueryEscape(object)) + } + path := "/printer/objects/query" + if len(escaped) > 0 { + path += "?" + strings.Join(escaped, "&") + } + resp, err := t.request(requestCtx, protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Method: http.MethodGet, + Path: path, + }) + if err != nil { + return nil, err + } + if resp.Type == protocol.MessageError { + return nil, fmt.Errorf("%s", resp.Error) + } + body, err := base64.StdEncoding.DecodeString(resp.Body) + if err != nil { + return nil, err + } + status, err := parseMoonrakerObjectStatus(body) + if err != nil { + return nil, err + } + if status == nil { + return nil, fmt.Errorf("missing status data") + } + return status, nil +} + +func (s *server) fetchPrinterJobHistory(ctx context.Context, t *tunnel) ([]map[string]any, error) { + id, err := newID() + if err != nil { + return nil, err + } + requestCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + resp, err := t.request(requestCtx, protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Method: http.MethodGet, + Path: "/server/history/list?limit=5&order=desc", + }) + if err != nil { + return nil, err + } + if resp.Type == protocol.MessageError { + return nil, fmt.Errorf("%s", resp.Error) + } + body, err := base64.StdEncoding.DecodeString(resp.Body) + if err != nil { + return nil, err + } + jobs, err := parseMoonrakerJobHistory(body) + if err != nil { + return nil, err + } + return jobs, nil +} + +func (s *server) fetchPrinterFileList(ctx context.Context, t *tunnel) ([]moonrakerFileInfo, error) { + id, err := newID() + if err != nil { + return nil, err + } + requestCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + resp, err := t.request(requestCtx, protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Method: http.MethodGet, + Path: "/server/files/list?root=gcodes", + }) + if err != nil { + return nil, err + } + if resp.Type == protocol.MessageError { + return nil, fmt.Errorf("%s", resp.Error) + } + body, err := base64.StdEncoding.DecodeString(resp.Body) + if err != nil { + return nil, err + } + files, err := parseMoonrakerFileList(body) + if err != nil { + return nil, err + } + return files, nil +} + +func (s *server) tunnelForPrinter(printerID string) *tunnel { + s.tunnelsMu.RLock() + defer s.tunnelsMu.RUnlock() + return s.tunnels[printerID] +} + +func (s *server) lastPrintableJobFilename(ctx context.Context, t *tunnel) (string, string, error) { + jobs, err := s.fetchPrinterJobHistory(ctx, t) + if err != nil { + return "", "", err + } + filename, status := selectLastPrintableJob(jobs) + if filename != "" { + return filename, status, nil + } + return "", "", fmt.Errorf("no completed print job was found in recent history") +} + +func (s *server) startPrinterJob(ctx context.Context, t *tunnel, filename string) error { + filename = strings.TrimSpace(filename) + if filename == "" { + return fmt.Errorf("filename is required") + } + id, err := newID() + if err != nil { + return err + } + requestCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + resp, err := t.request(requestCtx, protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Method: http.MethodPost, + Path: "/printer/print/start?filename=" + url.QueryEscape(filename), + }) + if err != nil { + return err + } + if resp.Type == protocol.MessageError { + return fmt.Errorf("%s", resp.Error) + } + if resp.Status < 200 || resp.Status >= 300 { + return fmt.Errorf("printer rejected print start with status %d", resp.Status) + } + return nil +} + +func (s *server) setPrinterHeaterTarget(ctx context.Context, t *tunnel, heater string, target float64) error { + heater = strings.TrimSpace(heater) + if heater == "" { + return fmt.Errorf("heater is required") + } + id, err := newID() + if err != nil { + return err + } + requestCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + script := fmt.Sprintf("SET_HEATER_TEMPERATURE HEATER=%s TARGET=%s", heater, strconv.FormatFloat(target, 'f', -1, 64)) + resp, err := t.request(requestCtx, protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Method: http.MethodPost, + Path: "/printer/gcode/script?script=" + url.QueryEscape(script), + }) + if err != nil { + return err + } + if resp.Type == protocol.MessageError { + return fmt.Errorf("%s", resp.Error) + } + if resp.Status < 200 || resp.Status >= 300 { + return fmt.Errorf("printer rejected heater target change with status %d", resp.Status) + } + return nil +} + +func isTerminalJobHistoryStatus(status string) bool { + switch strings.ToLower(strings.TrimSpace(status)) { + case "complete", "completed", "cancelled", "canceled", "failed", "error", "aborted": + return true + default: + return false + } +} + +func selectLastPrintableJob(jobs []map[string]any) (string, string) { + for _, job := range jobs { + filename := strings.TrimSpace(stringFromAny(job["filename"])) + if filename == "" { + continue + } + status := strings.ToLower(strings.TrimSpace(stringFromAny(job["status"]))) + if status == "" || isTerminalJobHistoryStatus(status) { + return filename, status + } + } + return "", "" +} + +type moonrakerFileInfo struct { + Path string `json:"path"` + Modified float64 `json:"modified"` + Size int64 `json:"size"` + Permissions string `json:"permissions"` +} + +func parseMoonrakerFileList(body []byte) ([]moonrakerFileInfo, error) { + trimmed := bytes.TrimSpace(body) + if len(trimmed) > 0 && trimmed[0] == '[' { + var arrayResult []moonrakerFileInfo + if err := json.Unmarshal(trimmed, &arrayResult); err != nil { + return nil, err + } + return arrayResult, nil + } + var parsed struct { + Result []moonrakerFileInfo `json:"result"` + Files []moonrakerFileInfo `json:"files"` + } + if err := json.Unmarshal(trimmed, &parsed); err != nil { + return nil, err + } + if len(parsed.Result) > 0 { + return parsed.Result, nil + } + return parsed.Files, nil +} + +func stringFromAny(value any) string { + switch v := value.(type) { + case string: + return v + case fmt.Stringer: + return v.String() + default: + return "" + } +} + +func parseMoonrakerPrintStatus(body []byte) (map[string]any, error) { + status, err := parseMoonrakerObjectStatus(body) + if err != nil { + return nil, err + } + return status, nil +} + +func parseMoonrakerObjectStatus(body []byte) (map[string]any, error) { + var parsed struct { + Result struct { + Status map[string]any `json:"status"` + } `json:"result"` + } + if err := json.Unmarshal(body, &parsed); err != nil { + return nil, err + } + return parsed.Result.Status, nil +} + +func parseMoonrakerJobHistory(body []byte) ([]map[string]any, error) { + var parsed struct { + Result struct { + Jobs []map[string]any `json:"jobs"` + } `json:"result"` + Jobs []map[string]any `json:"jobs"` + } + if err := json.Unmarshal(body, &parsed); err != nil { + return nil, err + } + if len(parsed.Result.Jobs) > 0 { + return parsed.Result.Jobs, nil + } + return parsed.Jobs, nil +} + +func printStatusFromHealth(health *protocol.Health) map[string]any { + if health == nil || health.PrintStatus == nil { + return nil + } + return map[string]any{ + "print_stats": map[string]any{ + "state": health.PrintStatus.State, + "filename": health.PrintStatus.Filename, + "message": health.PrintStatus.Message, + "print_duration": health.PrintStatus.PrintDuration, + "total_duration": health.PrintStatus.TotalDuration, + "filament_used": health.PrintStatus.FilamentUsed, + "estimated_time_remaining": health.PrintStatus.EstimatedTimeRemaining, + }, + "display_status": map[string]any{ + "progress": health.PrintStatus.Progress, + }, + "moonraker_status": health.PrintStatus.MoonrakerStatus, + "moonraker_metadata": health.PrintStatus.MoonrakerMetadata, + "layer_source": health.PrintStatus.LayerSource, + } +} + +func (s *server) handlePrinterProxy(w http.ResponseWriter, r *http.Request) { + if printerID, cameraName, cameraKind, ok := parseCameraPath(r.URL.Path); ok { + sess, ok := s.authorizePrinter(w, r, printerID, false) + if !ok { + return + } + if cameraKind == "stream" { + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("camera_view"), + PrinterID: printerID, + Detail: "opened camera stream", + }) + } + s.handleCameraProxy(w, r, printerID, cameraName, cameraKind) + return + } + + printerID, moonrakerPath, ok := parseProxyPath(r.URL.Path) + if !ok { + http.NotFound(w, r) + return + } + if r.URL.RawQuery != "" { + moonrakerPath += "?" + r.URL.RawQuery + } + controlRequest := !isReadOnlyMoonrakerRequest(r.Method, moonrakerPath) + sess, ok := s.authorizePrinter(w, r, printerID, controlRequest) + if !ok { + return + } + if s.controlModeForPrinter(printerID, nil) == "readonly" && !isReadOnlyMoonrakerRequest(r.Method, moonrakerPath) { + log.Printf("blocked read-only printer_id=%s method=%s path=%s", printerID, r.Method, moonrakerPath) + http.Error(w, "blocked by read-only printer control policy", http.StatusForbidden) + return + } + if isWebSocketUpgrade(r) { + enforceReadOnlyFrames := s.controlModeForPrinter(printerID, nil) == "readonly" + if controlRequest { + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("printer_ws_control"), + PrinterID: printerID, + Method: r.Method, + Path: moonrakerPath, + Detail: "opened Moonraker websocket", + }) + } + s.handleTunneledWebSocket(w, r, printerID, moonrakerPath, "moonraker_ws", enforceReadOnlyFrames, sess.Username) + return + } + + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + if t == nil { + http.Error(w, "printer agent is not connected", http.StatusBadGateway) + return + } + + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 32<<20)) + if err != nil { + http.Error(w, "failed to read request body", http.StatusBadRequest) + return + } + + id, err := newID() + if err != nil { + http.Error(w, "failed to create request id", http.StatusInternalServerError) + return + } + + msg := protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Method: r.Method, + Path: moonrakerPath, + Headers: moonrakerRequestHeaders(r.Header), + Body: base64.StdEncoding.EncodeToString(body), + } + + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + + resp, err := t.request(ctx, msg) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + if resp.Type == protocol.MessageError { + http.Error(w, resp.Error, http.StatusBadGateway) + return + } + + respBody, err := base64.StdEncoding.DecodeString(resp.Body) + if err != nil { + http.Error(w, "agent returned invalid response body", http.StatusBadGateway) + return + } + if strings.Contains(moonrakerPath, "/server/webcams/") { + respBody = rewriteMoonrakerWebcams(respBody, printerID) + } + + writeResponseHeaders(w, resp) + w.Header().Set("Cache-Control", "no-store, max-age=0") + if resp.Status == 0 { + resp.Status = http.StatusBadGateway + } + w.WriteHeader(resp.Status) + _, _ = w.Write(respBody) + if controlRequest { + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("printer_http_control"), + PrinterID: printerID, + Method: r.Method, + Path: moonrakerPath, + Status: resp.Status, + Detail: "proxied Moonraker control request", + }) + } + + log.Printf("proxied printer_id=%s method=%s path=%s status=%d", printerID, r.Method, moonrakerPath, resp.Status) +} + +func (s *server) handlePrinterSettingsAPI(w http.ResponseWriter, r *http.Request, printerID string) { + sess, ok := s.currentSession(r) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) + return + } + if sess.Role != "admin" { + http.Error(w, "admin access required", http.StatusForbidden) + return + } + + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + var health *protocol.Health + if t != nil { + t.healthMu.RLock() + health = t.health + t.healthMu.RUnlock() + } + + switch r.Method { + case http.MethodGet: + synced, state, detail := s.printerSettingsSyncStatus(printerID, health) + record := s.printerSettings.current(printerID, health, s.controlMode) + writeJSON(w, http.StatusOK, map[string]any{ + "printer_id": printerID, + "settings": s.publicPrinterSettings(record), + "control_mode": s.controlModeForPrinter(printerID, health), + "settings_synced": synced, + "settings_sync_state": state, + "settings_sync_detail": detail, + }) + case http.MethodPatch: + if !s.verifyCSRF(w, r, sess) { + return + } + before := s.printerSettings.current(printerID, health, s.controlMode) + var body struct { + DisplayName *string `json:"display_name"` + ControlMode *string `json:"control_mode"` + UIURL *string `json:"ui_url"` + UIAutoDetect *bool `json:"ui_auto_detect"` + NotificationSnapshotCamera *string `json:"notification_snapshot_camera"` + PrintNotificationsEnabled *bool `json:"print_notifications_enabled"` + NotifyPrintStarted *bool `json:"notify_print_started"` + NotifyPrintPaused *bool `json:"notify_print_paused"` + NotifyPrintResumed *bool `json:"notify_print_resumed"` + NotifyPrintCompleted *bool `json:"notify_print_completed"` + NotifyPrintCanceled *bool `json:"notify_print_canceled"` + NotifyPrintFailed *bool `json:"notify_print_failed"` + NotifyFirstLayer *bool `json:"notify_print_first_layer"` + NotifyThirdLayer *bool `json:"notify_print_third_layer"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + if body.NotificationSnapshotCamera != nil && health != nil && !notificationSnapshotCameraAllowed(health, *body.NotificationSnapshotCamera) { + http.Error(w, "notification snapshot camera must be blank or a snapshot-capable camera from the latest heartbeat", http.StatusBadRequest) + return + } + updated, err := s.printerSettings.update(printerID, body.DisplayName, body.ControlMode, body.UIURL, body.UIAutoDetect, body.NotificationSnapshotCamera, s.controlMode) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + updated, err = s.printerSettings.updateNotifications(printerID, body.PrintNotificationsEnabled, body.NotifyPrintStarted, body.NotifyPrintPaused, body.NotifyPrintResumed, body.NotifyPrintCompleted, body.NotifyPrintCanceled, body.NotifyPrintFailed, body.NotifyFirstLayer, body.NotifyThirdLayer) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if err := s.syncPrinterSettings(printerID); err != nil { + log.Printf("failed to sync printer settings printer_id=%s: %v", printerID, err) + } + synced, state, detail := s.printerSettingsSyncStatus(printerID, health) + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("printer_settings_update"), + PrinterID: printerID, + Detail: describePrinterSettingsChange(before, updated), + }) + writeJSON(w, http.StatusOK, map[string]any{ + "ok": true, + "printer_id": printerID, + "settings": s.publicPrinterSettings(updated), + "settings_synced": synced, + "settings_sync_state": state, + "settings_sync_detail": detail, + }) + default: + w.Header().Set("Allow", "GET, PATCH") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func (s *server) syncPrinterSettings(printerID string) error { + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + if t == nil { + return nil + } + record, ok := s.printerSettings.snapshot(printerID) + if !ok { + return nil + } + id, err := newID() + if err != nil { + return err + } + requestCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + resp, err := t.request(requestCtx, protocol.Message{ + ID: id, + Type: protocol.MessageConfigSync, + Settings: &protocol.Settings{ + ControlMode: record.ControlMode, + UIURL: record.UIURL, + UIAutoDetect: record.UIAutoDetect, + }, + }) + if err != nil { + return err + } + if resp.Type == protocol.MessageError { + return fmt.Errorf("%s", resp.Error) + } + if err := s.printerSettings.markSynced(printerID); err != nil { + return err + } + return nil +} + +func (s *server) controlModeForPrinter(printerID string, health *protocol.Health) string { + if record, ok := s.printerSettings.snapshot(printerID); ok { + if record.ControlMode != "" { + return record.ControlMode + } + } + return s.controlMode +} + +func (s *server) printerSettingsSyncStatus(printerID string, health *protocol.Health) (bool, string, string) { + record := s.printerSettings.current(printerID, health, s.controlMode) + if record.UpdatedAt.IsZero() { + return false, "Pending", "No printer settings have been saved yet." + } + if record.LastSyncedAt.IsZero() || record.LastSyncedAt.Before(record.UpdatedAt) { + if health == nil { + return false, "Pending", "Waiting for the agent to confirm the latest settings." + } + detail := "Waiting for the agent to confirm the latest settings." + if applied := strings.TrimSpace(health.ControlMode); applied != "" { + detail = fmt.Sprintf("%s Last heartbeat just now; applied mode %s.", detail, applied) + } else { + detail = fmt.Sprintf("%s Last heartbeat just now.", detail) + } + return false, "Pending", detail + } + return true, "Synced", "Agent acknowledged the latest saved settings." +} + +func describePrinterSettingsChange(before, after printerSettingsRecord) string { + var changes []string + if strings.TrimSpace(before.DisplayName) != strings.TrimSpace(after.DisplayName) { + changes = append(changes, fmt.Sprintf("display_name %q -> %q", strings.TrimSpace(before.DisplayName), strings.TrimSpace(after.DisplayName))) + } + if normalizeControlMode(before.ControlMode) != normalizeControlMode(after.ControlMode) { + changes = append(changes, fmt.Sprintf("control_mode %q -> %q", normalizeControlMode(before.ControlMode), normalizeControlMode(after.ControlMode))) + } + if strings.TrimSpace(before.UIURL) != strings.TrimSpace(after.UIURL) { + changes = append(changes, fmt.Sprintf("ui_url %q -> %q", strings.TrimSpace(before.UIURL), strings.TrimSpace(after.UIURL))) + } + if before.UIAutoDetect != after.UIAutoDetect { + changes = append(changes, fmt.Sprintf("ui_auto_detect %t -> %t", before.UIAutoDetect, after.UIAutoDetect)) + } + if strings.TrimSpace(before.NotificationSnapshotCamera) != strings.TrimSpace(after.NotificationSnapshotCamera) { + changes = append(changes, fmt.Sprintf("notification_snapshot_camera %q -> %q", strings.TrimSpace(before.NotificationSnapshotCamera), strings.TrimSpace(after.NotificationSnapshotCamera))) + } + if before.PrintNotificationsEnabled != after.PrintNotificationsEnabled { + changes = append(changes, fmt.Sprintf("print_notifications_enabled %t -> %t", before.PrintNotificationsEnabled, after.PrintNotificationsEnabled)) + } + if before.NotifyPrintStarted != after.NotifyPrintStarted { + changes = append(changes, fmt.Sprintf("notify_print_started %t -> %t", before.NotifyPrintStarted, after.NotifyPrintStarted)) + } + if before.NotifyPrintPaused != after.NotifyPrintPaused { + changes = append(changes, fmt.Sprintf("notify_print_paused %t -> %t", before.NotifyPrintPaused, after.NotifyPrintPaused)) + } + if before.NotifyPrintResumed != after.NotifyPrintResumed { + changes = append(changes, fmt.Sprintf("notify_print_resumed %t -> %t", before.NotifyPrintResumed, after.NotifyPrintResumed)) + } + if before.NotifyPrintCompleted != after.NotifyPrintCompleted { + changes = append(changes, fmt.Sprintf("notify_print_completed %t -> %t", before.NotifyPrintCompleted, after.NotifyPrintCompleted)) + } + if before.NotifyPrintCanceled != after.NotifyPrintCanceled { + changes = append(changes, fmt.Sprintf("notify_print_canceled %t -> %t", before.NotifyPrintCanceled, after.NotifyPrintCanceled)) + } + if before.NotifyPrintFailed != after.NotifyPrintFailed { + changes = append(changes, fmt.Sprintf("notify_print_failed %t -> %t", before.NotifyPrintFailed, after.NotifyPrintFailed)) + } + if before.NotifyFirstLayer != after.NotifyFirstLayer { + changes = append(changes, fmt.Sprintf("notify_print_first_layer %t -> %t", before.NotifyFirstLayer, after.NotifyFirstLayer)) + } + if before.NotifyThirdLayer != after.NotifyThirdLayer { + changes = append(changes, fmt.Sprintf("notify_print_third_layer %t -> %t", before.NotifyThirdLayer, after.NotifyThirdLayer)) + } + if len(changes) == 0 { + return "updated printer settings without field changes" + } + return "updated printer settings: " + strings.Join(changes, "; ") +} + +func (s *server) publicPrinterSettings(record printerSettingsRecord) map[string]any { + notificationReady, notificationSource := s.notificationDeliveryStatus() + settings := map[string]any{ + "printer_id": record.PrinterID, + "display_name": record.DisplayName, + "control_mode": record.ControlMode, + "ui_url": record.UIURL, + "ui_auto_detect": record.UIAutoDetect, + "notification_snapshot_camera": record.NotificationSnapshotCamera, + "updated_at": record.UpdatedAt, + "display_name_updated_at": record.DisplayNameUpdatedAt, + "last_synced_at": record.LastSyncedAt, + "install": record.Install, + "install_history": record.InstallHistory, + "print_notifications_enabled": record.PrintNotificationsEnabled, + "notify_print_started": record.NotifyPrintStarted, + "notify_print_paused": record.NotifyPrintPaused, + "notify_print_resumed": record.NotifyPrintResumed, + "notify_print_completed": record.NotifyPrintCompleted, + "notify_print_canceled": record.NotifyPrintCanceled, + "notify_print_failed": record.NotifyPrintFailed, + "notify_print_first_layer": record.NotifyFirstLayer, + "notify_print_third_layer": record.NotifyThirdLayer, + "notification_delivery_ready": notificationReady, + "notification_delivery_source": notificationSource, + "last_observed_print_state": record.LastObservedPrintState, + "last_observed_print_file": record.LastObservedPrintFile, + "last_observed_print_layer": record.LastObservedPrintLayer, + "last_observed_at": record.LastObservedAt, + "last_notified_print_state": record.LastNotifiedPrintState, + "last_notified_print_file": record.LastNotifiedPrintFile, + "last_notified_at": record.LastNotifiedAt, + "last_notification_source": record.LastNotificationSource, + "last_notification_error": record.LastNotificationError, + "last_layer_notified_print_layer": record.LastLayerNotifiedPrintLayer, + "last_layer_notified_at": record.LastLayerNotifiedAt, + "last_layer_notification_source": record.LastLayerNotificationSource, + "last_layer_notification_error": record.LastLayerNotificationError, + } + return settings +} + +func describeNotificationSettingsChange(before notificationSettingsRecord, after notificationSettingsRecord) string { + changes := make([]string, 0, 4) + if before.TelegramEnabled != after.TelegramEnabled { + changes = append(changes, fmt.Sprintf("telegram_enabled %t -> %t", before.TelegramEnabled, after.TelegramEnabled)) + } + if before.TelegramCommandsEnabled != after.TelegramCommandsEnabled { + changes = append(changes, fmt.Sprintf("telegram_commands_enabled %t -> %t", before.TelegramCommandsEnabled, after.TelegramCommandsEnabled)) + } + if before.TelegramBotToken != "" && after.TelegramBotToken == "" { + changes = append(changes, "telegram_bot_token cleared") + } else if before.TelegramBotToken == "" && after.TelegramBotToken != "" { + changes = append(changes, "telegram_bot_token configured") + } + if strings.TrimSpace(before.TelegramChatID) != strings.TrimSpace(after.TelegramChatID) { + changes = append(changes, fmt.Sprintf("telegram_chat_id %q -> %q", strings.TrimSpace(before.TelegramChatID), strings.TrimSpace(after.TelegramChatID))) + } + if len(changes) == 0 { + return "updated notification settings without field changes" + } + return "updated notification settings: " + strings.Join(changes, "; ") +} + +func (s *server) notificationDeliveryStatus() (bool, string) { + if s != nil && s.notificationSettings != nil { + global := s.notificationSettings.snapshot() + if global.TelegramEnabled && strings.TrimSpace(global.TelegramBotToken) != "" && strings.TrimSpace(global.TelegramChatID) != "" { + return true, "admin" + } + } + return false, "" +} + +func (s *server) handlePrinterAgentUpdateAPI(w http.ResponseWriter, r *http.Request, printerID string) { + if r.Method != http.MethodPost { + w.Header().Set("Allow", "POST") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + sess, ok := s.authorizePrinter(w, r, printerID, true) + if !ok { + return + } + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + if t == nil { + http.Error(w, "printer agent is not connected", http.StatusBadGateway) + return + } + record, ok := s.printerSettings.snapshot(printerID) + if !ok || record.Install == nil { + http.Error(w, "saved install details are required before upgrading the agent", http.StatusBadRequest) + return + } + releaseURL := strings.TrimSpace(record.Install.ReleaseURL) + if releaseURL == "" { + releaseURL = defaultReleaseBaseURL + } + reqID, err := newID() + if err != nil { + http.Error(w, "failed to create request", http.StatusInternalServerError) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute) + defer cancel() + resp, err := t.request(ctx, protocol.Message{ + ID: reqID, + Type: protocol.MessageAgentUpdate, + Update: &protocol.AgentUpdateRequest{ + ReleaseURL: releaseURL, + Version: serverVersion, + }, + }) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + if resp.Type == protocol.MessageError { + http.Error(w, resp.Error, http.StatusBadGateway) + return + } + connected, reconnectMessage, err := s.waitForPrinterConnection(r.Context(), printerID, 90*time.Second) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + updatedInstall := *record.Install + updatedInstall.ReleaseURL = releaseURL + updatedInstall.BinarySource = "agent-update" + updatedInstall.Message = "sent one-click agent update request" + updatedInstall.PostInstallConnected = connected + updatedInstall.PostInstallMessage = reconnectMessage + updatedInstall.RollbackPerformed = false + updatedInstall.RollbackMessage = "" + if connected { + updatedInstall.Status = "upgraded" + } else { + updatedInstall.Status = "failed" + updatedInstall.Error = "agent did not reconnect after update request" + } + updatedRecord, saveErr := s.printerSettings.updateInstall(printerID, updatedInstall) + if saveErr != nil { + log.Printf("failed to persist agent update record printer_id=%s: %v", printerID, saveErr) + updatedRecord = record + } + s.logAudit(auditEvent{ + Actor: sess.Username, + Action: actionLabel("printer_agent_update"), + PrinterID: printerID, + Detail: fmt.Sprintf("triggered agent update; reconnect=%t", connected), + }) + writeJSON(w, http.StatusOK, map[string]any{ + "ok": true, + "printer_id": printerID, + "settings": s.publicPrinterSettings(updatedRecord), + "connected": connected, + "reconnect_message": reconnectMessage, + "agent_update_version": serverVersion, + }) +} + +func (s *server) handleLegacyWebcamProxy(w http.ResponseWriter, r *http.Request) { + printerID, ok := legacyWebcamPrinterID(r) + if !ok { + http.Error(w, "printer context not found for webcam request", http.StatusNotFound) + return + } + if _, ok := s.authorizePrinter(w, r, printerID, false); !ok { + return + } + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + if t == nil { + http.Error(w, "printer agent is not connected", http.StatusBadGateway) + return + } + cameraName, kind := legacyWebcamTarget(t.health) + if cameraName == "" { + http.Error(w, "no camera is configured for this printer", http.StatusNotFound) + return + } + s.setPrinterContextCookie(w, printerID) + s.handleCameraProxy(w, r, printerID, cameraName, kind) +} + +func (s *server) handleUIProxy(w http.ResponseWriter, r *http.Request, printerID string, uiPath string, actor string) { + if uiPath == "/manifest.webmanifest" { + manifest := map[string]any{ + "name": "Fluidd", + "short_name": "Fluidd", + "description": "The Klipper web interface for managing your 3d printer", + "start_url": "./", + "scope": "./", + "display": "standalone", + "background_color": "#000000", + "theme_color": "#2196F3", + "lang": "en", + } + rewritten, err := json.Marshal(manifest) + if err != nil { + http.Error(w, "failed to render manifest", http.StatusInternalServerError) + return + } + s.setPrinterContextCookie(w, printerID) + w.Header().Set("Content-Type", "application/manifest+json") + w.Header().Set("Cache-Control", "no-store, max-age=0") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(rewritten) + return + } + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + if t == nil { + http.Error(w, "printer agent is not connected", http.StatusBadGateway) + return + } + s.setPrinterContextCookie(w, printerID) + if uiPath == "/" { + s.logAudit(auditEvent{ + Actor: actor, + Action: actionLabel("printer_ui_open"), + PrinterID: printerID, + Detail: "opened printer UI", + }) + } + if isWebSocketUpgrade(r) { + s.handleTunneledWebSocketWithTunnel(w, r, t, printerID, uiPath, "ui_ws", false, actor) + return + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 32<<20)) + if err != nil { + http.Error(w, "failed to read request body", http.StatusBadRequest) + return + } + uiPath = rewriteMoonrakerDatabaseNamespace(uiPath, printerID) + id, err := newID() + if err != nil { + http.Error(w, "failed to create request id", http.StatusInternalServerError) + return + } + resp, err := t.request(r.Context(), protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Target: "ui", + Method: r.Method, + Path: uiPath, + Headers: uiRequestHeaders(r.Header), + Body: base64.StdEncoding.EncodeToString(body), + }) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + if resp.Type == protocol.MessageError { + http.Error(w, resp.Error, http.StatusBadGateway) + return + } + respBody, err := base64.StdEncoding.DecodeString(resp.Body) + if err != nil { + http.Error(w, "agent returned invalid ui response body", http.StatusBadGateway) + return + } + writeResponseHeaders(w, resp) + w.Header().Set("Cache-Control", "no-store, max-age=0") + if uiPath == "/config.json" { + respBody = rewriteFluiddConfig(respBody, requestOrigin(r), printerID) + } + if uiPath == "/sw.js" { + w.Header().Set("Content-Type", "application/javascript") + w.Header().Set("Cache-Control", "no-store, max-age=0") + respBody = []byte(`self.addEventListener('install', event => { + self.skipWaiting(); +}); +self.addEventListener('activate', event => { + event.waitUntil(self.registration.unregister()); +});`) + } + if uiPath == "/manifest.webmanifest" { + w.Header().Set("Content-Type", "application/manifest+json") + } + respBody = rewriteUIResponse(resp.Headers, respBody, printerID) + if resp.Status == 0 { + resp.Status = http.StatusBadGateway + } + w.WriteHeader(resp.Status) + _, _ = w.Write(respBody) + log.Printf("proxied ui printer_id=%s method=%s path=%s status=%d", printerID, r.Method, uiPath, resp.Status) +} + +func uiRequestHeaders(h http.Header) []protocol.Header { + headers := make([]protocol.Header, 0, len(h)) + for name, values := range h { + if strings.EqualFold(name, "If-None-Match") || strings.EqualFold(name, "If-Modified-Since") || strings.EqualFold(name, "If-Range") { + continue + } + if strings.EqualFold(name, "Cache-Control") { + continue + } + headers = append(headers, protocol.Header{Name: name, Values: values}) + } + return headers +} + +func sanitizeUIProxyQuery(rawQuery string) string { + if rawQuery == "" { + return "" + } + values, err := url.ParseQuery(rawQuery) + if err != nil { + return "" + } + values.Del("printer") + return values.Encode() +} + +func rewriteMoonrakerDatabaseNamespace(path string, printerID string) string { + if !strings.HasPrefix(path, "/server/database/") { + return path + } + u, err := url.Parse(path) + if err != nil { + return path + } + values := u.Query() + namespace := values.Get("namespace") + if namespace == "" { + return path + } + if namespace == "fluidd" || strings.HasPrefix(namespace, "fluidd-") { + values.Set("namespace", "fluidd-"+printerID) + u.RawQuery = values.Encode() + return u.String() + } + return path +} + +func moonrakerRequestHeaders(h http.Header) []protocol.Header { + headers := make([]protocol.Header, 0, len(h)) + for name, values := range h { + if strings.EqualFold(name, "If-None-Match") || strings.EqualFold(name, "If-Modified-Since") || strings.EqualFold(name, "If-Range") { + continue + } + if strings.EqualFold(name, "Cache-Control") { + continue + } + headers = append(headers, protocol.Header{Name: name, Values: values}) + } + return headers +} + +func requestOrigin(r *http.Request) string { + scheme := "http" + if r.TLS != nil { + scheme = "https" + } + if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); forwarded != "" { + scheme = strings.ToLower(strings.Split(forwarded, ",")[0]) + } + return scheme + "://" + r.Host +} + +func (s *server) handleCameraProxy(w http.ResponseWriter, r *http.Request, printerID string, cameraName string, cameraKind string) { + if r.Method != http.MethodGet { + w.Header().Set("Allow", "GET") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + if t == nil { + http.Error(w, "printer agent is not connected", http.StatusBadGateway) + return + } + + id, err := newID() + if err != nil { + http.Error(w, "failed to create request id", http.StatusInternalServerError) + return + } + + msg := protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Target: "camera", + CameraName: cameraName, + CameraKind: cameraKind, + Method: http.MethodGet, + } + + if cameraKind == "snapshot" { + s.handleCameraSnapshot(w, r, t, msg, printerID, cameraName) + return + } + s.handleCameraStream(w, r, t, msg, printerID, cameraName) +} + +func (s *server) handleCameraSnapshot(w http.ResponseWriter, r *http.Request, t *tunnel, msg protocol.Message, printerID string, cameraName string) { + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + + responses, cleanup, err := t.openRequest(ctx, msg) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer cleanup() + + var header protocol.Message + select { + case header = <-responses: + case <-ctx.Done(): + http.Error(w, ctx.Err().Error(), http.StatusBadGateway) + return + case <-t.done: + http.Error(w, "agent disconnected", http.StatusBadGateway) + return + } + if header.Type == protocol.MessageError { + http.Error(w, header.Error, http.StatusBadGateway) + return + } + writeResponseHeaders(w, header) + w.Header().Set("Access-Control-Allow-Origin", "*") + if header.Status == 0 { + header.Status = http.StatusBadGateway + } + w.WriteHeader(header.Status) + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } + + for msg := range responses { + if msg.Type == protocol.MessageError { + log.Printf("camera snapshot error printer_id=%s camera=%s error=%s", printerID, cameraName, msg.Error) + return + } + if msg.Body != "" { + body, err := base64.StdEncoding.DecodeString(msg.Body) + if err != nil { + log.Printf("invalid camera snapshot chunk printer_id=%s camera=%s: %v", printerID, cameraName, err) + return + } + _, _ = w.Write(body) + } + if msg.End { + break + } + } + log.Printf("proxied camera snapshot printer_id=%s camera=%s status=%d", printerID, cameraName, header.Status) +} + +func (s *server) handleCameraStream(w http.ResponseWriter, r *http.Request, t *tunnel, msg protocol.Message, printerID string, cameraName string) { + responses, cleanup, err := t.openRequest(r.Context(), msg) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer cleanup() + + var header protocol.Message + select { + case header = <-responses: + case <-r.Context().Done(): + return + case <-t.done: + http.Error(w, "agent disconnected", http.StatusBadGateway) + return + } + if header.Type == protocol.MessageError { + http.Error(w, header.Error, http.StatusBadGateway) + return + } + writeResponseHeaders(w, header) + w.Header().Set("Access-Control-Allow-Origin", "*") + if header.Status == 0 { + header.Status = http.StatusBadGateway + } + w.WriteHeader(header.Status) + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } + + flusher, _ := w.(http.Flusher) + for { + select { + case <-r.Context().Done(): + log.Printf("camera stream closed printer_id=%s camera=%s", printerID, cameraName) + return + case msg, ok := <-responses: + if !ok { + return + } + if msg.Type == protocol.MessageError { + log.Printf("camera stream error printer_id=%s camera=%s error=%s", printerID, cameraName, msg.Error) + return + } + if msg.Body != "" { + body, err := base64.StdEncoding.DecodeString(msg.Body) + if err != nil { + log.Printf("invalid camera stream chunk printer_id=%s camera=%s: %v", printerID, cameraName, err) + return + } + if _, err := w.Write(body); err != nil { + return + } + if flusher != nil { + flusher.Flush() + } + } + if msg.End { + return + } + } + } +} + +func isWebSocketUpgrade(r *http.Request) bool { + return strings.EqualFold(r.Header.Get("Upgrade"), "websocket") +} + +func (s *server) handleTunneledWebSocket(w http.ResponseWriter, r *http.Request, printerID string, upstreamPath string, target string, enforceReadOnlyFrames bool, actor string) { + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + if t == nil { + http.Error(w, "printer agent is not connected", http.StatusBadGateway) + return + } + s.handleTunneledWebSocketWithTunnel(w, r, t, printerID, upstreamPath, target, enforceReadOnlyFrames, actor) +} + +func (s *server) handleTunneledWebSocketWithTunnel(w http.ResponseWriter, r *http.Request, t *tunnel, printerID string, upstreamPath string, target string, enforceReadOnlyFrames bool, actor string) { + id, err := newID() + if err != nil { + http.Error(w, "failed to create request id", http.StatusInternalServerError) + return + } + + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + + responses, cleanup, err := t.openRequest(ctx, protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Target: target, + Method: http.MethodGet, + Path: upstreamPath, + Headers: headersFromHTTP(r.Header), + }) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer cleanup() + + var header protocol.Message + select { + case header = <-responses: + case <-ctx.Done(): + http.Error(w, ctx.Err().Error(), http.StatusBadGateway) + return + case <-t.done: + http.Error(w, "agent disconnected", http.StatusBadGateway) + return + } + if header.Type == protocol.MessageError { + http.Error(w, header.Error, http.StatusBadGateway) + return + } + if header.Status != http.StatusSwitchingProtocols { + http.Error(w, "upstream websocket did not upgrade", http.StatusBadGateway) + return + } + + client, err := s.upgrader.Upgrade(w, r, nil) + if err != nil { + sendTunnelWebSocketEnd(t, id) + return + } + defer client.Close() + defer sendTunnelWebSocketEnd(t, id) + + done := make(chan struct{}, 2) + var clientWriteMu sync.Mutex + + go func() { + defer func() { done <- struct{}{} }() + for { + messageType, payload, err := client.ReadMessage() + if err != nil { + return + } + if enforceReadOnlyFrames && !isReadOnlyMoonrakerWebSocketPayload(payload) { + log.Printf("blocked read-only websocket printer_id=%s path=%s payload=%s", printerID, upstreamPath, string(payload)) + s.logAudit(auditEvent{ + Actor: actor, + Action: actionLabel("printer_ws_blocked"), + PrinterID: printerID, + Path: upstreamPath, + Detail: "blocked read-only websocket control payload", + }) + clientWriteMu.Lock() + _ = client.WriteJSON(readOnlyWebSocketError(payload)) + clientWriteMu.Unlock() + continue + } + if !isReadOnlyMoonrakerWebSocketPayload(payload) { + s.logAudit(auditEvent{ + Actor: actor, + Action: actionLabel("printer_ws_control"), + PrinterID: printerID, + Path: upstreamPath, + Detail: "proxied Moonraker websocket control payload", + }) + } + if err := sendTunnelWebSocketFrame(t, id, messageType, payload); err != nil { + return + } + } + }() + + go func() { + defer func() { done <- struct{}{} }() + for { + select { + case msg := <-responses: + if msg.Type == protocol.MessageError { + log.Printf("websocket tunnel error printer_id=%s path=%s error=%s", printerID, upstreamPath, msg.Error) + return + } + if msg.End { + return + } + if msg.Body == "" { + continue + } + payload, err := base64.StdEncoding.DecodeString(msg.Body) + if err != nil { + return + } + messageType := msg.WSMessageType + if messageType != websocket.BinaryMessage && messageType != websocket.TextMessage { + messageType = websocket.TextMessage + } + clientWriteMu.Lock() + err = client.WriteMessage(messageType, payload) + clientWriteMu.Unlock() + if err != nil { + return + } + case <-t.done: + return + case <-r.Context().Done(): + return + } + } + }() + + <-done + log.Printf("proxied websocket printer_id=%s target=%s path=%s", printerID, target, upstreamPath) +} + +func sendTunnelWebSocketFrame(t *tunnel, id string, messageType int, payload []byte) error { + msg := protocol.Message{ + ID: id, + Target: "ws_frame", + Body: base64.StdEncoding.EncodeToString(payload), + WSMessageType: messageType, + } + t.writeMu.Lock() + err := t.conn.WriteJSON(msg) + t.writeMu.Unlock() + return err +} + +func sendTunnelWebSocketEnd(t *tunnel, id string) { + t.writeMu.Lock() + _ = t.conn.WriteJSON(protocol.Message{ID: id, Target: "ws_frame", End: true}) + t.writeMu.Unlock() +} + +func parsePrinterAPIPath(path string) (printerID string, action string, ok bool) { + rest := strings.TrimPrefix(path, "/api/printers/") + if rest == path { + return "", "", false + } + parts := strings.Split(strings.Trim(rest, "/"), "/") + if len(parts) == 1 && parts[0] != "" { + return parts[0], "", true + } + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", "", false + } + return parts[0], parts[1], true +} + +func parsePrinterUIPath(path string) (printerID string, uiPath string, ok bool) { + rest := strings.TrimPrefix(path, "/printers/") + if rest == path { + return "", "", false + } + parts := strings.SplitN(rest, "/", 3) + if len(parts) < 2 || parts[0] == "" || parts[1] != "ui" { + return "", "", false + } + if len(parts) == 2 { + return parts[0], "/", true + } + return parts[0], "/" + parts[2], true +} + +func parsePrinterRootPath(path string) (printerID string, ok bool) { + rest := strings.TrimPrefix(path, "/printers/") + if rest == path { + return "", false + } + parts := strings.Split(strings.Trim(rest, "/"), "/") + if len(parts) != 1 || parts[0] == "" { + return "", false + } + return parts[0], true +} + +func parsePrinterSettingsPath(path string) (printerID string, ok bool) { + rest := strings.TrimPrefix(path, "/printers/") + if rest == path { + return "", false + } + parts := strings.Split(strings.Trim(rest, "/"), "/") + if len(parts) != 2 || parts[0] == "" || parts[1] != "settings" { + return "", false + } + return parts[0], true +} + +func parsePrinterAgentPath(path string) (printerID string, ok bool) { + rest := strings.TrimPrefix(path, "/printers/") + if rest == path { + return "", false + } + parts := strings.Split(strings.Trim(rest, "/"), "/") + if len(parts) != 2 || parts[0] == "" || parts[1] != "agent" { + return "", false + } + return parts[0], true +} + +func parseCameraPath(path string) (printerID string, cameraName string, cameraKind string, ok bool) { + rest := strings.TrimPrefix(path, "/p/") + if rest == path { + return "", "", "", false + } + parts := strings.Split(strings.Trim(rest, "/"), "/") + if len(parts) != 4 || parts[1] != "camera" || parts[0] == "" || parts[2] == "" { + return "", "", "", false + } + if parts[3] != "snapshot" && parts[3] != "stream" { + return "", "", "", false + } + return parts[0], parts[2], parts[3], true +} + +func parseProxyPath(path string) (printerID string, moonrakerPath string, ok bool) { + rest := strings.TrimPrefix(path, "/p/") + if rest == path { + return "", "", false + } + parts := strings.SplitN(rest, "/", 3) + if len(parts) != 3 || parts[0] == "" || parts[1] != "moonraker" { + return "", "", false + } + return parts[0], "/" + parts[2], true +} + +func legacyWebcamPrinterID(r *http.Request) (string, bool) { + if cookie, err := r.Cookie("ka_printer_context"); err == nil { + if printerID := strings.TrimSpace(cookie.Value); printerID != "" { + return printerID, true + } + } + for _, candidate := range []string{r.Referer(), r.Header.Get("Origin")} { + if candidate == "" { + continue + } + u, err := url.Parse(candidate) + if err != nil { + continue + } + if printerID, _, ok := parsePrinterUIPath(u.Path); ok && printerID != "" { + return printerID, true + } + } + return "", false +} + +func (s *server) setPrinterContextCookie(w http.ResponseWriter, printerID string) { + if printerID == "" { + return + } + http.SetCookie(w, &http.Cookie{ + Name: "ka_printer_context", + Value: printerID, + Path: "/", + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: s.cookieSecure, + }) +} + +func legacyWebcamTarget(health *protocol.Health) (cameraName string, kind string) { + if health == nil { + return "", "snapshot" + } + for _, camera := range health.Cameras { + if camera.Name == "" { + continue + } + if camera.HasSnapshot { + return camera.Name, "snapshot" + } + if camera.HasStream { + return camera.Name, "stream" + } + } + return "", "snapshot" +} + +func (t *tunnel) request(ctx context.Context, msg protocol.Message) (protocol.Message, error) { + ch, cleanup, err := t.openRequest(ctx, msg) + if err != nil { + return protocol.Message{}, err + } + defer cleanup() + + select { + case resp := <-ch: + return resp, nil + case <-ctx.Done(): + return protocol.Message{}, ctx.Err() + case <-t.done: + return protocol.Message{}, fmt.Errorf("agent disconnected") + } +} + +func (t *tunnel) openRequest(ctx context.Context, msg protocol.Message) (<-chan protocol.Message, func(), error) { + ch := make(chan protocol.Message, 64) + + t.pendingMu.Lock() + t.pending[msg.ID] = ch + t.pendingMu.Unlock() + + cleanup := func() { + t.pendingMu.Lock() + delete(t.pending, msg.ID) + t.pendingMu.Unlock() + } + + t.writeMu.Lock() + err := t.conn.WriteJSON(msg) + t.writeMu.Unlock() + if err != nil { + cleanup() + return nil, nil, err + } + + return ch, cleanup, nil +} + +func (s *server) handlePrinterHeartbeat(printerID string, health *protocol.Health) { + if s == nil || s.printerSettings == nil || health == nil { + return + } + _, created, err := s.printerSettings.ensureFromHealth(printerID, health, s.controlMode) + if err != nil { + log.Printf("failed to seed printer settings printer_id=%s: %v", printerID, err) + return + } + if created { + go func() { + if err := s.syncPrinterSettings(printerID); err != nil { + log.Printf("failed to sync seeded printer settings printer_id=%s: %v", printerID, err) + } + }() + if health.PrintStatus != nil { + if _, err := s.printerSettings.updatePrintObservation(printerID, health.PrintStatus, "", false, ""); err != nil { + log.Printf("failed to seed print observation printer_id=%s: %v", printerID, err) + } + } + return + } + if health.PrintStatus != nil { + s.maybeNotifyPrinterPrintStatus(printerID, health) + } +} + +func (s *server) maybeNotifyPrinterPrintStatus(printerID string, health *protocol.Health) { + if s == nil || s.printerSettings == nil || health == nil || health.PrintStatus == nil { + return + } + record, ok := s.printerSettings.snapshot(printerID) + if !ok { + return + } + currentState := strings.TrimSpace(health.PrintStatus.State) + currentFile := strings.TrimSpace(health.PrintStatus.Filename) + currentLayer := health.PrintStatus.CurrentLayer + previousState := strings.TrimSpace(record.LastObservedPrintState) + previousLayer := record.LastObservedPrintLayer + if record.LastObservedAt.IsZero() && previousState == "" { + if _, err := s.printerSettings.updatePrintObservation(printerID, health.PrintStatus, "", false, ""); err != nil { + log.Printf("failed to seed print observation printer_id=%s: %v", printerID, err) + } + if _, err := s.printerSettings.updatePrintLayerObservation(printerID, &protocol.PrintStatus{CurrentLayer: 0}, "", false, ""); err != nil { + log.Printf("failed to seed print layer observation printer_id=%s: %v", printerID, err) + } + return + } + event := printerNotificationEvent(previousState, currentState) + shouldNotify := record.PrintNotificationsEnabled && event != "" && isPrinterNotificationEventEnabled(record, event) + layerEvents := printerLayerNotificationEventsForStatus(previousLayer, health.PrintStatus) + layerShouldNotifyAny := false + for _, layerEvent := range layerEvents { + if record.PrintNotificationsEnabled && isPrinterLayerNotificationEventEnabled(record, layerEvent) { + layerShouldNotifyAny = true + break + } + } + var snapshot []byte + var snapshotName string + if (shouldNotify || layerShouldNotifyAny) && s.notifier != nil { + if data, name, err := s.capturePrinterNotificationSnapshot(printerID, health); err != nil { + log.Printf("failed to capture notification snapshot printer_id=%s: %v", printerID, err) + } else { + snapshot = data + snapshotName = name + } + } + if (shouldNotify || layerShouldNotifyAny) && s.notifier != nil && len(snapshot) == 0 { + log.Printf("sending notification without snapshot printer_id=%s", printerID) + } + notificationSource := "" + notificationError := "" + notified := false + if shouldNotify && s.notifier != nil { + notificationSource = "telegram" + if err := s.notifier.NotifyPrinterPrintStatus(context.Background(), printerID, record, health, snapshot, snapshotName); err != nil { + notificationError = err.Error() + log.Printf("failed to send telegram notification printer_id=%s: %v", printerID, err) + } else { + notified = true + } + } + if _, err := s.printerSettings.updatePrintObservation(printerID, &protocol.PrintStatus{ + State: currentState, + Filename: currentFile, + }, notificationSource, notified, notificationError); err != nil { + log.Printf("failed to persist print observation printer_id=%s: %v", printerID, err) + } + layerNotificationSource := "" + layerNotificationError := "" + layerNotified := false + for _, layerEvent := range layerEvents { + layerShouldNotify := record.PrintNotificationsEnabled && isPrinterLayerNotificationEventEnabled(record, layerEvent) + if !layerShouldNotify || s.notifier == nil { + continue + } + layerNotificationSource = "telegram" + if err := s.notifier.NotifyPrinterLayerStatus(context.Background(), printerID, record, health, layerEvent, snapshot, snapshotName); err != nil { + layerNotificationError = err.Error() + log.Printf("failed to send telegram layer notification printer_id=%s event=%s: %v", printerID, layerEvent, err) + } else { + layerNotified = true + } + } + if shouldPersistPrinterLayerObservation(health.PrintStatus) { + if _, err := s.printerSettings.updatePrintLayerObservation(printerID, &protocol.PrintStatus{ + State: currentState, + Filename: currentFile, + CurrentLayer: currentLayer, + }, layerNotificationSource, layerNotified, layerNotificationError); err != nil { + log.Printf("failed to persist print layer observation printer_id=%s: %v", printerID, err) + } + } +} + +func (s *server) capturePrinterNotificationSnapshot(printerID string, health *protocol.Health) ([]byte, string, error) { + return s.capturePrinterNotificationSnapshotWithCamera(printerID, health, "") +} + +func (s *server) capturePrinterNotificationSnapshotWithCamera(printerID string, health *protocol.Health, preferredCamera string) ([]byte, string, error) { + if s == nil || health == nil { + return nil, "", fmt.Errorf("printer health unavailable") + } + record, _ := s.printerSettings.snapshot(printerID) + cameraName, _ := notificationSnapshotCamera(health, record.NotificationSnapshotCamera) + preferredCamera = strings.TrimSpace(preferredCamera) + if preferredCamera != "" { + name, camera := notificationSnapshotCamera(health, preferredCamera) + if name == "" || camera == nil { + return nil, "", fmt.Errorf("camera %q is not snapshot-capable", preferredCamera) + } + cameraName = name + } + if cameraName == "" { + return nil, "", fmt.Errorf("no snapshot-capable camera configured") + } + s.tunnelsMu.RLock() + t := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + if t == nil { + return nil, "", fmt.Errorf("printer agent is not connected") + } + id, err := newID() + if err != nil { + return nil, "", err + } + msg := protocol.Message{ + ID: id, + Type: protocol.MessageHTTPRequest, + Target: "camera_snapshot", + CameraName: cameraName, + CameraKind: "snapshot", + Method: http.MethodGet, + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + responses, cleanup, err := t.openRequest(ctx, msg) + if err != nil { + return nil, "", err + } + defer cleanup() + var header protocol.Message + select { + case header = <-responses: + case <-ctx.Done(): + return nil, "", ctx.Err() + case <-t.done: + return nil, "", fmt.Errorf("agent disconnected") + } + if header.Type == protocol.MessageError { + return nil, "", fmt.Errorf(header.Error) + } + if header.End { + if header.Body == "" { + return nil, "", fmt.Errorf("empty camera snapshot") + } + data, err := base64.StdEncoding.DecodeString(header.Body) + if err != nil { + return nil, "", err + } + if len(data) == 0 { + return nil, "", fmt.Errorf("empty camera snapshot") + } + if header.Status < 200 || header.Status >= 300 { + return nil, "", fmt.Errorf("camera snapshot failed: status %d", header.Status) + } + return data, cameraName, nil + } + var snapshot bytes.Buffer + for response := range responses { + if response.Type == protocol.MessageError { + return nil, "", fmt.Errorf(response.Error) + } + if response.Body != "" { + chunk, err := base64.StdEncoding.DecodeString(response.Body) + if err != nil { + return nil, "", err + } + if _, err := snapshot.Write(chunk); err != nil { + return nil, "", err + } + } + if response.End { + break + } + } + if snapshot.Len() == 0 { + return nil, "", fmt.Errorf("empty camera snapshot") + } + return snapshot.Bytes(), cameraName, nil +} + +func notificationSnapshotCamera(health *protocol.Health, preferred string) (string, *protocol.CameraHealth) { + if health == nil { + return "", nil + } + preferred = strings.TrimSpace(preferred) + if preferred != "" { + for i := range health.Cameras { + camera := &health.Cameras[i] + if camera == nil || strings.TrimSpace(camera.Name) != preferred { + continue + } + if camera.HasSnapshot { + return camera.Name, camera + } + return "", nil + } + } + for i := range health.Cameras { + camera := &health.Cameras[i] + if camera == nil || strings.TrimSpace(camera.Name) == "" { + continue + } + if camera.HasSnapshot { + return camera.Name, camera + } + } + return "", nil +} + +func notificationSnapshotCameraAllowed(health *protocol.Health, preferred string) bool { + preferred = strings.TrimSpace(preferred) + if preferred == "" { + return true + } + if health == nil { + return false + } + for i := range health.Cameras { + camera := &health.Cameras[i] + if camera != nil && strings.TrimSpace(camera.Name) == preferred && camera.HasSnapshot { + return true + } + } + return false +} + +func printerNotificationEvent(previousState string, currentState string) string { + previousState = strings.ToLower(strings.TrimSpace(previousState)) + currentState = strings.ToLower(strings.TrimSpace(currentState)) + if currentState == "" || currentState == previousState { + return "" + } + switch currentState { + case "printing": + if previousState == "paused" { + return "resumed" + } + return "started" + case "paused": + return "paused" + case "complete", "completed": + return "completed" + case "cancelled", "canceled": + return "canceled" + case "error", "failed": + return "failed" + default: + return "" + } +} + +func printerLayerNotificationEvents(previousLayer int, currentLayer int, currentState string) []string { + if strings.ToLower(strings.TrimSpace(currentState)) != "printing" { + return nil + } + if currentLayer <= 0 || currentLayer == previousLayer { + return nil + } + if currentLayer < previousLayer { + previousLayer = 0 + } + events := make([]string, 0, 2) + if previousLayer < 2 && currentLayer >= 2 { + events = append(events, "first_layer") + } + if previousLayer < 4 && currentLayer >= 4 { + events = append(events, "third_layer") + } + return events +} + +func printerLayerNotificationEventsForStatus(previousLayer int, status *protocol.PrintStatus) []string { + if !printerLayerNotificationsTrusted(status) { + return nil + } + return printerLayerNotificationEvents(previousLayer, status.CurrentLayer, status.State) +} + +func printerLayerNotificationsTrusted(status *protocol.PrintStatus) bool { + if status == nil { + return false + } + state := strings.ToLower(strings.TrimSpace(status.State)) + if state != "printing" { + return true + } + if status.CurrentLayer <= 0 { + return true + } + source := strings.ToLower(strings.TrimSpace(status.LayerSource)) + if source == "" { + return true + } + if strings.Contains(source, "print_stats") { + return true + } + return false +} + +func shouldPersistPrinterLayerObservation(status *protocol.PrintStatus) bool { + if !printerLayerNotificationsTrusted(status) { + return false + } + if status == nil { + return false + } + state := strings.ToLower(strings.TrimSpace(status.State)) + if state == "printing" && status.CurrentLayer <= 0 { + return false + } + return true +} + +func printerLayerNotificationEvent(previousLayer int, currentLayer int, currentState string) string { + events := printerLayerNotificationEvents(previousLayer, currentLayer, currentState) + if len(events) == 0 { + return "" + } + return events[0] +} + +func isPrinterNotificationEventEnabled(record printerSettingsRecord, event string) bool { + if !record.PrintNotificationsEnabled { + return false + } + switch event { + case "started": + return record.NotifyPrintStarted + case "paused": + return record.NotifyPrintPaused + case "resumed": + return record.NotifyPrintResumed + case "completed": + return record.NotifyPrintCompleted + case "canceled": + return record.NotifyPrintCanceled + case "failed": + return record.NotifyPrintFailed + default: + return false + } +} + +func isPrinterLayerNotificationEventEnabled(record printerSettingsRecord, event string) bool { + if !record.PrintNotificationsEnabled { + return false + } + switch event { + case "first_layer": + return record.NotifyFirstLayer + case "third_layer": + return record.NotifyThirdLayer + default: + return false + } +} + +func (t *tunnel) readLoop(s *server) { + defer close(t.done) + + for { + var msg protocol.Message + if err := t.conn.ReadJSON(&msg); err != nil { + log.Printf("agent read loop ended printer_id=%s remote=%s error=%v", t.printerID, t.remoteAddr, err) + return + } + + if msg.Type == protocol.MessageHeartbeat && msg.Health != nil { + t.healthMu.Lock() + t.health = msg.Health + t.healthMu.Unlock() + go s.handlePrinterHeartbeat(t.printerID, msg.Health) + log.Printf("heartbeat printer_id=%s moonraker_reachable=%t state=%s", t.printerID, msg.Health.MoonrakerReachable, msg.Health.MoonrakerState) + continue + } + + t.pendingMu.Lock() + ch := t.pending[msg.ID] + t.pendingMu.Unlock() + + if ch == nil { + log.Printf("received response for unknown request id=%s printer_id=%s", msg.ID, t.printerID) + continue + } + ch <- msg + } +} + +func (t *tunnel) close() { + _ = t.conn.Close() +} + +func (t *tunnel) acceptsDuplicateBlock(now time.Time) bool { + if t == nil { + return false + } + select { + case <-t.done: + return false + default: + } + t.healthMu.RLock() + health := t.health + t.healthMu.RUnlock() + if health != nil && health.CheckedAtUnix > 0 { + checkedAt := time.Unix(health.CheckedAtUnix, 0) + return now.Sub(checkedAt) < 45*time.Second + } + if !t.connectedAt.IsZero() { + return now.Sub(t.connectedAt) < 45*time.Second + } + return true +} + +func headersFromHTTP(h http.Header) []protocol.Header { + headers := make([]protocol.Header, 0, len(h)) + for name, values := range h { + headers = append(headers, protocol.Header{Name: name, Values: values}) + } + return headers +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if err := json.NewEncoder(w).Encode(value); err != nil { + log.Printf("failed to write json response: %v", err) + } +} + +func writeResponseHeaders(w http.ResponseWriter, msg protocol.Message) { + for _, h := range msg.Headers { + if strings.EqualFold(h.Name, "Content-Length") || + strings.EqualFold(h.Name, "Content-Encoding") || + strings.EqualFold(h.Name, "Transfer-Encoding") || + strings.EqualFold(h.Name, "Connection") || + strings.EqualFold(h.Name, "Keep-Alive") || + strings.EqualFold(h.Name, "Proxy-Authenticate") || + strings.EqualFold(h.Name, "Proxy-Authorization") || + strings.EqualFold(h.Name, "TE") || + strings.EqualFold(h.Name, "Trailer") || + strings.EqualFold(h.Name, "Upgrade") { + continue + } + for _, v := range h.Values { + w.Header().Add(h.Name, v) + } + } +} + +func rewriteUIResponse(headers []protocol.Header, body []byte, printerID string) []byte { + contentType := "" + for _, h := range headers { + if strings.EqualFold(h.Name, "Content-Type") && len(h.Values) > 0 { + contentType = h.Values[0] + break + } + } + if !strings.Contains(contentType, "text/html") && !strings.Contains(contentType, "javascript") && !strings.Contains(contentType, "application/json") && !strings.Contains(contentType, "text/css") { + return body + } + text := string(body) + isHTML := strings.Contains(contentType, "text/html") + uiPrefix := "/printers/" + printerID + "/ui" + moonrakerPrefix := "/p/" + printerID + "/moonraker" + replacements := []struct{ old, new string }{ + {`http://127.0.0.1:7125/websocket`, moonrakerPrefix + `/websocket`}, + {`https://127.0.0.1:7125/websocket`, moonrakerPrefix + `/websocket`}, + {`ws://127.0.0.1:7125/websocket`, moonrakerPrefix + `/websocket`}, + {`wss://127.0.0.1:7125/websocket`, moonrakerPrefix + `/websocket`}, + {`http://localhost:7125/websocket`, moonrakerPrefix + `/websocket`}, + {`https://localhost:7125/websocket`, moonrakerPrefix + `/websocket`}, + {`ws://localhost:7125/websocket`, moonrakerPrefix + `/websocket`}, + {`wss://localhost:7125/websocket`, moonrakerPrefix + `/websocket`}, + {`http://127.0.0.1:7125`, moonrakerPrefix}, + {`https://127.0.0.1:7125`, moonrakerPrefix}, + {`ws://127.0.0.1:7125`, moonrakerPrefix + `/websocket`}, + {`wss://127.0.0.1:7125`, moonrakerPrefix + `/websocket`}, + {`http://localhost:7125`, moonrakerPrefix}, + {`https://localhost:7125`, moonrakerPrefix}, + {`ws://localhost:7125`, moonrakerPrefix + `/websocket`}, + {`wss://localhost:7125`, moonrakerPrefix + `/websocket`}, + {`href="/`, `href="` + uiPrefix + `/`}, + {`src="/`, `src="` + uiPrefix + `/`}, + {`action="/`, `action="` + uiPrefix + `/`}, + {`url("/`, `url("` + uiPrefix + `/`}, + {`url('/`, `url('` + uiPrefix + `/`}, + {`fetch("/`, `fetch("` + moonrakerPrefix + `/`}, + {`fetch('/`, `fetch('` + moonrakerPrefix + `/`}, + {`"/printer/`, `"` + moonrakerPrefix + `/printer/`}, + {`'/printer/`, `'` + moonrakerPrefix + `/printer/`}, + {`"/server/`, `"` + moonrakerPrefix + `/server/`}, + {`'/server/`, `'` + moonrakerPrefix + `/server/`}, + } + for _, replacement := range replacements { + text = strings.ReplaceAll(text, replacement.old, replacement.new) + } + if isHTML { + text = injectPrinterUIResetScript(text, printerID) + } + return []byte(text) +} + +func injectPrinterUIResetScript(text string, printerID string) string { + script := `` + if strings.Contains(text, "") { + return strings.Replace(text, "", ""+script, 1) + } + if strings.Contains(text, "") { + return strings.Replace(text, "", script+"", 1) + } + return script + text +} + +func rewriteFluiddConfig(body []byte, origin string, printerID string) []byte { + var config map[string]any + if err := json.Unmarshal(body, &config); err != nil { + return body + } + config["endpoints"] = []string{origin + "/p/" + printerID + "/moonraker"} + rewritten, err := json.MarshalIndent(config, "", " ") + if err != nil { + return body + } + return append(rewritten, '\n') +} + +func rewriteMoonrakerWebcams(body []byte, printerID string) []byte { + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + return body + } + result, _ := payload["result"].(map[string]any) + if result == nil { + result = payload + } + webcams, _ := result["webcams"].([]any) + if len(webcams) > 0 { + for _, item := range webcams { + webcam, ok := item.(map[string]any) + if !ok { + continue + } + name, _ := webcam["name"].(string) + if name == "" { + continue + } + if streamURL, _ := webcam["stream_url"].(string); streamURL != "" { + webcam["stream_url"] = "/p/" + printerID + "/camera/" + url.PathEscape(name) + "/stream" + } + if snapshotURL, _ := webcam["snapshot_url"].(string); snapshotURL != "" { + webcam["snapshot_url"] = "/p/" + printerID + "/camera/" + url.PathEscape(name) + "/snapshot" + } + if service, _ := webcam["service"].(string); service == "mjpegstreamer-adaptive" { + webcam["service"] = "mjpegstreamer" + } + } + } + if streamURL, _ := result["stream_url"].(string); streamURL != "" { + if name, _ := result["name"].(string); name != "" { + result["stream_url"] = "/p/" + printerID + "/camera/" + url.PathEscape(name) + "/stream" + } + } + if snapshotURL, _ := result["snapshot_url"].(string); snapshotURL != "" { + if name, _ := result["name"].(string); name != "" { + result["snapshot_url"] = "/p/" + printerID + "/camera/" + url.PathEscape(name) + "/snapshot" + } + } + rewritten, err := json.MarshalIndent(payload, "", " ") + if err != nil { + return body + } + return append(rewritten, '\n') +} + +func isReadOnlyMoonrakerRequest(method string, path string) bool { + if method == http.MethodGet || method == http.MethodHead || method == http.MethodOptions { + return true + } + cleanPath := path + if i := strings.Index(cleanPath, "?"); i >= 0 { + cleanPath = cleanPath[:i] + } + blockedPrefixes := []string{ + "/printer/gcode/script", + "/printer/print/", + "/printer/emergency_stop", + "/printer/firmware_restart", + "/printer/restart", + "/printer/objects/subscribe", + "/server/files", + "/server/machine", + "/machine", + "/printer/toolhead", + "/printer/bed_mesh", + } + for _, prefix := range blockedPrefixes { + if strings.HasPrefix(cleanPath, prefix) { + return false + } + } + return false +} + +func isReadOnlyMoonrakerWebSocketPayload(payload []byte) bool { + var message map[string]any + if err := json.Unmarshal(payload, &message); err != nil { + return true + } + method, _ := message["method"].(string) + if method == "" { + return true + } + blockedPrefixes := []string{ + "printer.gcode.script", + "printer.print.", + "printer.emergency_stop", + "printer.firmware_restart", + "printer.restart", + "server.files.upload", + "server.files.delete", + } + for _, prefix := range blockedPrefixes { + if strings.HasPrefix(method, prefix) { + return false + } + } + return true +} + +func readOnlyWebSocketError(payload []byte) map[string]any { + var message map[string]any + _ = json.Unmarshal(payload, &message) + response := map[string]any{ + "jsonrpc": "2.0", + "error": map[string]any{ + "code": http.StatusForbidden, + "message": "blocked by read-only printer control policy", + }, + } + if id, ok := message["id"]; ok { + response["id"] = id + } + return response +} + +func constantTimeEqual(a string, b string) bool { + if len(a) != len(b) { + return false + } + return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 +} + +func newLoginLimiter(limit int, window time.Duration) *loginLimiter { + return &loginLimiter{ + attempts: make(map[string]loginAttempt), + limit: limit, + window: window, + } +} + +func (l *loginLimiter) allow(key string) bool { + now := time.Now() + l.mu.Lock() + defer l.mu.Unlock() + + attempt := l.attempts[key] + if now.After(attempt.WindowEnds) { + attempt = loginAttempt{WindowEnds: now.Add(l.window)} + } + attempt.Count++ + l.attempts[key] = attempt + return attempt.Count <= l.limit +} + +func (l *loginLimiter) reset(key string) { + l.mu.Lock() + delete(l.attempts, key) + l.mu.Unlock() +} + +func requestIP(r *http.Request) string { + forwarded := r.Header.Get("X-Forwarded-For") + if forwarded != "" { + return strings.TrimSpace(strings.Split(forwarded, ",")[0]) + } + host := r.RemoteAddr + if i := strings.LastIndex(host, ":"); i > -1 { + return host[:i] + } + return host +} + +func envOrDefault(key string, fallback string) string { + value := strings.TrimSpace(os.Getenv(key)) + if value == "" { + return fallback + } + return value +} + +func envBool(key string) bool { + switch strings.ToLower(strings.TrimSpace(os.Getenv(key))) { + case "1", "true", "yes", "on": + return true + default: + return false + } +} + +func warnIfDevelopmentSecrets(agentToken string, adminUser string, adminPass string, cookieSecure bool) { + if agentToken == "dev-token" { + log.Printf("WARNING: using default KA_AGENT_TOKEN/dev-token; replace it before exposing the server") + } + if adminUser == "admin" && adminPass == "admin" { + log.Printf("WARNING: using default admin credentials admin/admin; replace them before exposing the server") + } + if !cookieSecure { + log.Printf("WARNING: session cookies are not marked Secure; set KA_COOKIE_SECURE=true when serving over HTTPS") + } +} + +func newID() (string, error) { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "", err + } + return hex.EncodeToString(b[:]), nil +} + +func init() { + log.SetFlags(log.LstdFlags | log.Lmicroseconds) +} + diff --git a/cmd/server/main_test.go b/cmd/server/main_test.go new file mode 100644 index 0000000..5fb1e8b --- /dev/null +++ b/cmd/server/main_test.go @@ -0,0 +1,1582 @@ +package main + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "net/url" + "mime/multipart" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/klipperanywhere/klipperanywhere/internal/protocol" +) + +type roundTripperFunc func(*http.Request) (*http.Response, error) + +func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +func TestParseProxyPath(t *testing.T) { + printerID, path, ok := parseProxyPath("/p/test/moonraker/printer/info") + if !ok { + t.Fatal("expected path to parse") + } + if printerID != "test" { + t.Fatalf("printer id = %q, want test", printerID) + } + if path != "/printer/info" { + t.Fatalf("path = %q, want /printer/info", path) + } +} + +func TestParseCameraPath(t *testing.T) { + printerID, camera, kind, ok := parseCameraPath("/p/real-printer/camera/Camera/snapshot") + if !ok { + t.Fatal("expected camera path to parse") + } + if printerID != "real-printer" || camera != "Camera" || kind != "snapshot" { + t.Fatalf("got %q %q %q", printerID, camera, kind) + } +} + +func TestNotificationSnapshotCamera(t *testing.T) { + health := &protocol.Health{Cameras: []protocol.CameraHealth{ + {Name: "wide", HasSnapshot: true}, + {Name: "nozzle", HasSnapshot: true}, + {Name: "stream-only", HasSnapshot: false, HasStream: true}, + }} + + name, camera := notificationSnapshotCamera(health, "") + if name != "wide" || camera == nil || camera.Name != "wide" { + t.Fatalf("default camera = %q %#v, want wide", name, camera) + } + + name, camera = notificationSnapshotCamera(health, "nozzle") + if name != "nozzle" || camera == nil || camera.Name != "nozzle" { + t.Fatalf("preferred camera = %q %#v, want nozzle", name, camera) + } + + name, camera = notificationSnapshotCamera(health, "missing") + if name != "wide" || camera == nil || camera.Name != "wide" { + t.Fatalf("missing preferred camera = %q %#v, want wide fallback", name, camera) + } + + name, camera = notificationSnapshotCamera(health, "stream-only") + if name != "" || camera != nil { + t.Fatalf("non-snapshot preferred camera = %q %#v, want none", name, camera) + } +} + +func TestNotificationSnapshotCameraAllowed(t *testing.T) { + health := &protocol.Health{Cameras: []protocol.CameraHealth{ + {Name: "wide", HasSnapshot: true}, + {Name: "stream-only", HasSnapshot: false, HasStream: true}, + }} + + if !notificationSnapshotCameraAllowed(health, "") { + t.Fatal("blank preferred camera should be allowed") + } + if !notificationSnapshotCameraAllowed(health, "wide") { + t.Fatal("snapshot-capable camera should be allowed") + } + if notificationSnapshotCameraAllowed(health, "stream-only") { + t.Fatal("stream-only camera should not be allowed") + } + if notificationSnapshotCameraAllowed(health, "missing") { + t.Fatal("missing camera should not be allowed") + } +} + +func TestNotificationSettingsStoreDefaultsCommandsToDelivery(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "notification-settings.json") + if err := os.WriteFile(path, []byte(`{"telegram_enabled":true,"telegram_bot_token":"bot123","telegram_chat_id":"chat456"}`), 0o600); err != nil { + t.Fatalf("failed to write settings file: %v", err) + } + store, err := newNotificationSettingsStore(path) + if err != nil { + t.Fatalf("newNotificationSettingsStore returned error: %v", err) + } + snapshot := store.snapshot() + if !snapshot.TelegramEnabled { + t.Fatal("expected telegram delivery to remain enabled") + } + if !snapshot.TelegramCommandsEnabled { + t.Fatal("expected telegram commands to default to delivery state for legacy settings") + } +} + +func TestPublicNotificationSettingsIncludesCommandsToggle(t *testing.T) { + settings := publicNotificationSettings(notificationSettingsRecord{ + TelegramEnabled: true, + TelegramCommandsEnabled: false, + TelegramBotToken: "bot123", + TelegramChatID: "chat456", + }) + if got, ok := settings["telegram_commands_enabled"].(bool); !ok || got { + t.Fatalf("telegram_commands_enabled = %v, want false", settings["telegram_commands_enabled"]) + } +} + +func TestParsePrinterAPIPath(t *testing.T) { + printerID, action, ok := parsePrinterAPIPath("/api/printers/test") + if !ok { + t.Fatal("expected printer detail path to parse") + } + if printerID != "test" || action != "" { + t.Fatalf("got %q %q", printerID, action) + } + + printerID, action, ok = parsePrinterAPIPath("/api/printers/test/health") + if !ok { + t.Fatal("expected printer health path to parse") + } + if printerID != "test" || action != "health" { + t.Fatalf("got %q %q", printerID, action) + } +} + +func TestParsePrinterUIPath(t *testing.T) { + printerID, path, ok := parsePrinterUIPath("/printers/test/ui/") + if !ok { + t.Fatal("expected printer ui path to parse") + } + if printerID != "test" || path != "/" { + t.Fatalf("got %q %q", printerID, path) + } + + printerID, path, ok = parsePrinterUIPath("/printers/test/ui/assets/app.js") + if !ok { + t.Fatal("expected nested printer ui path to parse") + } + if printerID != "test" || path != "/assets/app.js" { + t.Fatalf("got %q %q", printerID, path) + } +} + +func TestParsePrinterRootPath(t *testing.T) { + printerID, ok := parsePrinterRootPath("/printers/test") + if !ok || printerID != "test" { + t.Fatalf("got %q %t", printerID, ok) + } +} + +func TestParsePrinterSettingsPath(t *testing.T) { + printerID, ok := parsePrinterSettingsPath("/printers/test/settings") + if !ok || printerID != "test" { + t.Fatalf("got %q %t", printerID, ok) + } + if _, ok := parsePrinterSettingsPath("/printers/test/ui"); ok { + t.Fatal("ui path should not parse as settings path") + } +} + +func TestParsePrinterAgentPath(t *testing.T) { + printerID, ok := parsePrinterAgentPath("/printers/test/agent") + if !ok || printerID != "test" { + t.Fatalf("got %q %t", printerID, ok) + } + if _, ok := parsePrinterAgentPath("/printers/test/settings"); ok { + t.Fatal("settings path should not parse as agent path") + } +} + +func TestLegacyWebcamPrinterIDCookieFallback(t *testing.T) { + r := &http.Request{Header: http.Header{}} + r.AddCookie(&http.Cookie{Name: "ka_printer_context", Value: "real-printer"}) + printerID, ok := legacyWebcamPrinterID(r) + if !ok { + t.Fatal("expected cookie fallback to resolve printer id") + } + if printerID != "real-printer" { + t.Fatalf("printer id = %q, want real-printer", printerID) + } +} + +func TestPublicPrinterUIAsset(t *testing.T) { + if !isPublicPrinterUIAsset("/printers/real-printer/ui/manifest.webmanifest") { + t.Fatal("manifest should be public") + } + if !isPublicPrinterUIAsset("/printers/real-printer/ui/sw.js") { + t.Fatal("sw should be public") + } + if isPublicPrinterUIAsset("/printers/real-printer/ui/assets/app.js") { + t.Fatal("regular assets should not be public by default") + } +} + +func TestRewriteUIResponse(t *testing.T) { + body := []byte(``) + rewritten := string(rewriteUIResponse([]protocol.Header{{ + Name: "Content-Type", + Values: []string{"text/html; charset=utf-8"}, + }}, body, "test")) + + for _, want := range []string{ + `href="/printers/test/ui/assets/app.css"`, + `src="/printers/test/ui/assets/app.js"`, + `fetch("/p/test/moonraker/printer/info")`, + `"/p/test/moonraker"`, + `"/p/test/moonraker/websocket"`, + `window.__KA_PRINTER_ID = "test"`, + `window.__KA_UI_PRINTER_TOKEN = "test"`, + `rewriteWebSocketUrl`, + `proto.getItem = function`, + } { + if !strings.Contains(rewritten, want) { + t.Fatalf("rewritten response missing %q in %s", want, rewritten) + } + } +} + +func TestInjectPrinterUIResetScript(t *testing.T) { + rewritten := injectPrinterUIResetScript(``, "rockchip") + for _, want := range []string{ + `currentUrl.searchParams.set("printer", "rockchip")`, + `window.__KA_PRINTER_ID = "rockchip"`, + `window.__KA_UI_PRINTER_TOKEN = "rockchip"`, + `var storagePrefix = "ka-ui-rockchip:"`, + `window.WebSocket`, + } { + if !strings.Contains(rewritten, want) { + t.Fatalf("injected script missing %q in %s", want, rewritten) + } + } +} + +func TestInjectPrinterUIResetScriptIsPrinterSpecific(t *testing.T) { + rockchip := injectPrinterUIResetScript(``, "rockchip") + f005 := injectPrinterUIResetScript(``, "f005-020b") + + for _, want := range []string{ + `currentUrl.searchParams.set("printer", "rockchip")`, + `window.__KA_PRINTER_ID = "rockchip"`, + `window.__KA_UI_PRINTER_TOKEN = "rockchip"`, + `var storagePrefix = "ka-ui-rockchip:"`, + `/p/rockchip/moonraker/websocket`, + } { + if !strings.Contains(rockchip, want) { + t.Fatalf("rockchip script missing %q in %s", want, rockchip) + } + } + + for _, want := range []string{ + `currentUrl.searchParams.set("printer", "f005-020b")`, + `window.__KA_PRINTER_ID = "f005-020b"`, + `window.__KA_UI_PRINTER_TOKEN = "f005-020b"`, + `var storagePrefix = "ka-ui-f005-020b:"`, + `/p/f005-020b/moonraker/websocket`, + } { + if !strings.Contains(f005, want) { + t.Fatalf("f005 script missing %q in %s", want, f005) + } + } + + if rockchip == f005 { + t.Fatal("expected printer bootstrap scripts to differ between printers") + } +} + +func TestSanitizeUIProxyQuery(t *testing.T) { + if got := sanitizeUIProxyQuery("printer=abc123&foo=bar"); got != "foo=bar" { + t.Fatalf("unexpected sanitized query: %q", got) + } + if got := sanitizeUIProxyQuery("foo=bar&printer=abc123"); got != "foo=bar" { + t.Fatalf("unexpected sanitized query order: %q", got) + } + if got := sanitizeUIProxyQuery("foo=bar"); got != "foo=bar" { + t.Fatalf("unexpected passthrough query: %q", got) + } +} + +func TestRewriteMoonrakerDatabaseNamespace(t *testing.T) { + got := rewriteMoonrakerDatabaseNamespace("/server/database/item?namespace=fluidd", "rockchip") + if got != "/server/database/item?namespace=fluidd-rockchip" { + t.Fatalf("unexpected rewritten database namespace: %q", got) + } + got = rewriteMoonrakerDatabaseNamespace("/server/database/item?namespace=fluidd", "f005-020b") + if got != "/server/database/item?namespace=fluidd-f005-020b" { + t.Fatalf("unexpected rewritten database namespace for f005: %q", got) + } + got = rewriteMoonrakerDatabaseNamespace("/server/database/item?namespace=fluidd-rockchip", "rockchip") + if got != "/server/database/item?namespace=fluidd-rockchip" { + t.Fatalf("unexpected preserved database namespace: %q", got) + } + got = rewriteMoonrakerDatabaseNamespace("/server/database/item?namespace=other", "rockchip") + if got != "/server/database/item?namespace=other" { + t.Fatalf("unexpected non-fluidd namespace rewrite: %q", got) + } +} + +func TestRewriteFluiddConfig(t *testing.T) { + body := []byte(`{"blacklist":["fluidd.xyz"],"endpoints":[],"hosted":false}`) + rewritten := string(rewriteFluiddConfig(body, "https://example.com", "real-printer")) + if !strings.Contains(rewritten, `"endpoints": [`) { + t.Fatalf("rewritten config missing endpoints array: %s", rewritten) + } + if !strings.Contains(rewritten, `https://example.com/p/real-printer/moonraker`) { + t.Fatalf("rewritten config missing printer endpoint: %s", rewritten) + } +} + +func TestRewriteMoonrakerWebcams(t *testing.T) { + body := []byte(`{"result":{"webcams":[{"name":"Camera","service":"mjpegstreamer-adaptive","stream_url":"/webcam/?action=stream","snapshot_url":"/webcam/?action=snapshot"}]}}`) + rewritten := string(rewriteMoonrakerWebcams(body, "real-printer")) + if !strings.Contains(rewritten, `/p/real-printer/camera/Camera/stream`) { + t.Fatalf("rewritten webcams missing stream url: %s", rewritten) + } + if !strings.Contains(rewritten, `/p/real-printer/camera/Camera/snapshot`) { + t.Fatalf("rewritten webcams missing snapshot url: %s", rewritten) + } + if !strings.Contains(rewritten, `"service": "mjpegstreamer"`) { + t.Fatalf("rewritten webcams missing normalized service: %s", rewritten) + } +} + +func TestParseMoonrakerPrintStatus(t *testing.T) { + body := []byte(`{"result":{"status":{"print_stats":{"state":"printing","filename":"benchy.gcode","print_duration":12.5,"total_duration":24.5,"filament_used":34.2},"display_status":{"progress":0.5}}}}`) + status, err := parseMoonrakerPrintStatus(body) + if err != nil { + t.Fatalf("parseMoonrakerPrintStatus returned error: %v", err) + } + printStats, ok := status["print_stats"].(map[string]any) + if !ok { + t.Fatalf("missing print_stats: %+v", status) + } + if got, _ := printStats["state"].(string); got != "printing" { + t.Fatalf("state = %q, want printing", got) + } + if got, _ := printStats["filename"].(string); got != "benchy.gcode" { + t.Fatalf("filename = %q, want benchy.gcode", got) + } + displayStatus, ok := status["display_status"].(map[string]any) + if !ok { + t.Fatalf("missing display_status: %+v", status) + } + if got, _ := displayStatus["progress"].(float64); got != 0.5 { + t.Fatalf("progress = %v, want 0.5", got) + } +} + +func TestPrintStatusFromHealth(t *testing.T) { + status := printStatusFromHealth(&protocol.Health{ + PrintStatus: &protocol.PrintStatus{ + State: "printing", + Filename: "benchy.gcode", + Message: "Printing benchy", + Progress: 0.5, + PrintDuration: 12.5, + TotalDuration: 24.5, + FilamentUsed: 34.2, + EstimatedTimeRemaining: 120.0, + MoonrakerStatus: map[string]any{ + "print_stats": map[string]any{"state": "printing"}, + }, + MoonrakerMetadata: map[string]any{ + "metadata": map[string]any{"layer_height": 0.2}, + }, + LayerSource: "metadata", + }, + }) + if status == nil { + t.Fatal("expected cached print status") + } + printStats, ok := status["print_stats"].(map[string]any) + if !ok { + t.Fatalf("missing print_stats: %+v", status) + } + if got, _ := printStats["state"].(string); got != "printing" { + t.Fatalf("state = %q, want printing", got) + } + displayStatus, ok := status["display_status"].(map[string]any) + if !ok { + t.Fatalf("missing display_status: %+v", status) + } + if got, _ := displayStatus["progress"].(float64); got != 0.5 { + t.Fatalf("progress = %v, want 0.5", got) + } + if _, ok := status["moonraker_status"].(map[string]any); !ok { + t.Fatalf("missing moonraker_status: %+v", status) + } + if _, ok := status["moonraker_metadata"].(map[string]any); !ok { + t.Fatalf("missing moonraker_metadata: %+v", status) + } + if got, _ := status["layer_source"].(string); got != "metadata" { + t.Fatalf("layer_source = %q, want metadata", got) + } +} + +func TestParseMoonrakerJobHistory(t *testing.T) { + body := []byte(`{"result":{"jobs":[{"filename":"benchy.gcode","status":"completed","total_duration":3600.0,"print_duration":3555.0,"start_time":100,"end_time":200,"message":"done"}]}}`) + jobs, err := parseMoonrakerJobHistory(body) + if err != nil { + t.Fatalf("parseMoonrakerJobHistory returned error: %v", err) + } + if len(jobs) != 1 { + t.Fatalf("jobs length = %d, want 1", len(jobs)) + } + if got, _ := jobs[0]["filename"].(string); got != "benchy.gcode" { + t.Fatalf("filename = %q, want benchy.gcode", got) + } +} + +func TestRequestOrigin(t *testing.T) { + r := &http.Request{ + Header: http.Header{ + "X-Forwarded-Proto": []string{"https"}, + }, + Host: "printer.example.com", + } + if got := requestOrigin(r); got != "https://printer.example.com" { + t.Fatalf("requestOrigin = %q, want https://printer.example.com", got) + } +} + +func TestRequestAgentTunnelURL(t *testing.T) { + if got := requestAgentTunnelURL("https://printer.example.com"); got != "wss://printer.example.com/agent/tunnel" { + t.Fatalf("requestAgentTunnelURL = %q", got) + } + if got := requestAgentTunnelURL("http://printer.example.com"); got != "ws://printer.example.com/agent/tunnel" { + t.Fatalf("requestAgentTunnelURL = %q", got) + } +} + +func TestOriginIsLoopback(t *testing.T) { + for _, origin := range []string{ + "http://127.0.0.1:8080", + "https://localhost", + "http://[::1]:8080", + } { + if !originIsLoopback(origin) { + t.Fatalf("expected %q to be loopback", origin) + } + } + if originIsLoopback("https://klipperanywhere.example.com") { + t.Fatal("expected public origin to be non-loopback") + } +} + +func TestReleaseAssetForMachine(t *testing.T) { + tests := map[string]string{ + "amd64": "klipperanywhere-agent-linux-amd64", + "aarch64": "klipperanywhere-agent-linux-arm64", + "armv7l": "klipperanywhere-agent-linux-armv7", + "mipsel": "klipperanywhere-agent-linux-mipsle", + } + for machine, want := range tests { + got, err := releaseAssetForMachine(machine) + if err != nil { + t.Fatalf("releaseAssetForMachine(%q) returned error: %v", machine, err) + } + if got != want { + t.Fatalf("releaseAssetForMachine(%q) = %q, want %q", machine, got, want) + } + } +} + +func TestDescribeLoadedAgentBinary(t *testing.T) { + tests := map[string]string{ + "source": "Built agent binary from the server container source.", + "bundled": "Loaded bundled agent binary from the server container.", + "release": "Downloaded release agent binary from https://example.test/releases.", + } + for source, want := range tests { + if got := describeLoadedAgentBinary(source, "https://example.test/releases"); got != want { + t.Fatalf("describeLoadedAgentBinary(%q) = %q, want %q", source, got, want) + } + } +} + +func TestBuildSSHInstallConfig(t *testing.T) { + uiAutoDetect := false + body := buildSSHInstallConfig("https://printer.example.com", "real-printer", "agent-token", sshInstallRequest{ + MoonrakerURL: "http://192.168.1.60:7125", + UIURL: "http://192.168.1.60", + UIAutoDetect: &uiAutoDetect, + }) + text := string(body) + for _, want := range []string{ + `"server_url": "wss://printer.example.com/agent/tunnel"`, + `"printer_id": "real-printer"`, + `"token": "agent-token"`, + `"moonraker_url": "http://192.168.1.60:7125"`, + `"ui_url": "http://192.168.1.60"`, + `"ui_auto_detect": false`, + } { + if !strings.Contains(text, want) { + t.Fatalf("config missing %q: %s", want, text) + } + } +} + +func TestBuildSSHInstallConfigWithStateFile(t *testing.T) { + body := buildSSHInstallConfigWithStateFile("https://printer.example.com", "real-printer", "agent-token", sshInstallRequest{}, "/useremain/home/rinkhals/apps/60-klipperanywhere-agent/agent-state.json") + text := string(body) + if !strings.Contains(text, `"state_file": "/useremain/home/rinkhals/apps/60-klipperanywhere-agent/agent-state.json"`) { + t.Fatalf("config missing state_file: %s", text) + } +} + +func TestNormalizeInstallHostType(t *testing.T) { + tests := map[string]string{ + "": installHostTypeStandard, + "standard": installHostTypeStandard, + "Rinkhals": installHostTypeRinkhals, + "unknown": installHostTypeStandard, + " rinkhals ": installHostTypeRinkhals, + } + for input, want := range tests { + if got := normalizeInstallHostType(input); got != want { + t.Fatalf("normalizeInstallHostType(%q) = %q, want %q", input, got, want) + } + } +} + +func TestResolveInstallServerURL(t *testing.T) { + got, err := resolveInstallServerURL("http://127.0.0.1:8080", "https://printer.example.com") + if err != nil { + t.Fatalf("resolveInstallServerURL returned error: %v", err) + } + if got != "https://printer.example.com" { + t.Fatalf("resolveInstallServerURL = %q, want https://printer.example.com", got) + } + + if _, err := resolveInstallServerURL("http://127.0.0.1:8080", "http://localhost:8080"); err == nil { + t.Fatal("expected loopback server url to be rejected") + } + + got, err = resolveInstallServerURL("https://printer.example.com", "") + if err != nil { + t.Fatalf("resolveInstallServerURL fallback returned error: %v", err) + } + if got != "https://printer.example.com" { + t.Fatalf("resolveInstallServerURL fallback = %q, want https://printer.example.com", got) + } +} + +func TestMoonrakerRequestHeaders(t *testing.T) { + headers := moonrakerRequestHeaders(http.Header{ + "If-None-Match": []string{"abc"}, + "If-Modified-Since": []string{"yesterday"}, + "If-Range": []string{"range"}, + "Cache-Control": []string{"max-age=0"}, + "Accept": []string{"application/json"}, + }) + for _, h := range headers { + if strings.EqualFold(h.Name, "If-None-Match") || strings.EqualFold(h.Name, "If-Modified-Since") || strings.EqualFold(h.Name, "If-Range") || strings.EqualFold(h.Name, "Cache-Control") { + t.Fatalf("unexpected header preserved: %s", h.Name) + } + } + foundAccept := false + for _, h := range headers { + if strings.EqualFold(h.Name, "Accept") { + foundAccept = true + } + } + if !foundAccept { + t.Fatal("expected Accept header to be preserved") + } +} + +func TestWriteResponseHeadersStripsHopByHopHeaders(t *testing.T) { + w := httptest.NewRecorder() + writeResponseHeaders(w, protocol.Message{ + Headers: []protocol.Header{ + {Name: "Content-Type", Values: []string{"multipart/x-mixed-replace; boundary=frame"}}, + {Name: "Content-Length", Values: []string{"123"}}, + {Name: "Transfer-Encoding", Values: []string{"chunked"}}, + {Name: "Connection", Values: []string{"keep-alive"}}, + {Name: "Keep-Alive", Values: []string{"timeout=5"}}, + {Name: "Cache-Control", Values: []string{"no-cache"}}, + }, + }) + if got := w.Header().Get("Content-Type"); got != "multipart/x-mixed-replace; boundary=frame" { + t.Fatalf("content-type = %q", got) + } + if got := w.Header().Get("Cache-Control"); got != "no-cache" { + t.Fatalf("cache-control = %q", got) + } + for _, name := range []string{"Content-Length", "Transfer-Encoding", "Connection", "Keep-Alive"} { + if got := w.Header().Get(name); got != "" { + t.Fatalf("%s should be stripped, got %q", name, got) + } + } +} + +func TestUIProxySpecialPaths(t *testing.T) { + manifest := httptest.NewRecorder() + manifest.WriteHeader(http.StatusOK) + manifestBody := []byte(`{"name":"fluidd"}`) + manifestHeader := protocol.Message{ + Headers: []protocol.Header{{Name: "Content-Type", Values: []string{"application/octet-stream"}}}, + } + writeResponseHeaders(manifest, manifestHeader) + manifest.Header().Set("Cache-Control", "no-store, max-age=0") + manifest.Header().Set("Content-Type", "application/manifest+json") + if got := manifest.Header().Get("Content-Type"); got != "application/manifest+json" { + t.Fatalf("manifest content-type = %q", got) + } + _ = manifestBody + + sw := httptest.NewRecorder() + writeResponseHeaders(sw, protocol.Message{}) + sw.Header().Set("Content-Type", "application/javascript") + if got := sw.Header().Get("Content-Type"); got != "application/javascript" { + t.Fatalf("sw content-type = %q", got) + } +} + +func TestReadOnlyMoonrakerRequestPolicy(t *testing.T) { + tests := []struct { + method string + path string + want bool + }{ + {http.MethodGet, "/printer/info", true}, + {http.MethodPost, "/printer/gcode/script", false}, + {http.MethodPost, "/server/files/upload", false}, + {http.MethodPost, "/printer/print/pause", false}, + {http.MethodPost, "/printer/print/cancel", false}, + {http.MethodPost, "/printer/emergency_stop", false}, + } + for _, tt := range tests { + if got := isReadOnlyMoonrakerRequest(tt.method, tt.path); got != tt.want { + t.Fatalf("isReadOnlyMoonrakerRequest(%q, %q) = %t, want %t", tt.method, tt.path, got, tt.want) + } + } +} + +func TestReadOnlyMoonrakerWebSocketPolicy(t *testing.T) { + tests := []struct { + payload string + want bool + }{ + {`{"jsonrpc":"2.0","method":"printer.objects.subscribe","id":1}`, true}, + {`{"jsonrpc":"2.0","method":"server.info","id":2}`, true}, + {`{"jsonrpc":"2.0","method":"server.files.get_directory","id":5}`, true}, + {`{"jsonrpc":"2.0","method":"printer.gcode.script","id":3}`, false}, + {`{"jsonrpc":"2.0","method":"printer.print.pause","id":4}`, false}, + {`{"jsonrpc":"2.0","method":"server.files.upload","id":6}`, false}, + } + for _, tt := range tests { + if got := isReadOnlyMoonrakerWebSocketPayload([]byte(tt.payload)); got != tt.want { + t.Fatalf("isReadOnlyMoonrakerWebSocketPayload(%s) = %t, want %t", tt.payload, got, tt.want) + } + } +} + +func TestControlModeForPrinterUsesStoredSettings(t *testing.T) { + s := &server{ + controlMode: "readonly", + printerSettings: &printerSettingsStore{ + records: map[string]printerSettingsRecord{ + "real-printer": { + PrinterID: "real-printer", + ControlMode: "full", + }, + }, + }, + } + if got := s.controlModeForPrinter("real-printer", &protocol.Health{ControlMode: "readonly"}); got != "full" { + t.Fatalf("controlModeForPrinter = %q, want full", got) + } + if got := s.controlModeForPrinter("missing", nil); got != "readonly" { + t.Fatalf("controlModeForPrinter = %q, want readonly", got) + } +} + +func TestPrinterSettingsSyncStatus(t *testing.T) { + s := &server{ + controlMode: "readonly", + printerSettings: &printerSettingsStore{ + records: map[string]printerSettingsRecord{ + "real-printer": { + PrinterID: "real-printer", + ControlMode: "full", + UIURL: "http://192.168.1.60", + UIAutoDetect: false, + UpdatedAt: time.Now().UTC(), + LastSyncedAt: time.Now().UTC(), + }, + }, + }, + } + synced, state, detail := s.printerSettingsSyncStatus("real-printer", &protocol.Health{ + ControlMode: "full", + UIURL: "http://192.168.1.60", + UIAutoDetect: false, + }) + if !synced || state != "Synced" { + t.Fatalf("expected synced state, got synced=%t state=%q detail=%q", synced, state, detail) + } + + s.printerSettings.records["real-printer"] = printerSettingsRecord{ + PrinterID: "real-printer", + ControlMode: "full", + UIURL: "http://192.168.1.60", + UIAutoDetect: false, + UpdatedAt: time.Now().UTC(), + LastSyncedAt: time.Time{}, + } + synced, state, detail = s.printerSettingsSyncStatus("real-printer", &protocol.Health{ + ControlMode: "readonly", + UIURL: "http://192.168.1.60", + UIAutoDetect: false, + }) + if synced || state != "Pending" { + t.Fatalf("expected pending state, got synced=%t state=%q detail=%q", synced, state, detail) + } + if !strings.Contains(detail, "Waiting for the agent to confirm the latest settings.") { + t.Fatalf("pending detail missing confirmation text: %q", detail) + } +} + +func TestTelegramNotifierSendTestNotification(t *testing.T) { + var gotRequest *http.Request + var gotBody string + notifier := &telegramNotifier{ + client: &http.Client{ + Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) { + gotRequest = req + body, _ := io.ReadAll(req.Body) + gotBody = string(body) + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), + Header: make(http.Header), + Request: req, + }, nil + }), + }, + settings: ¬ificationSettingsStore{ + record: notificationSettingsRecord{ + TelegramEnabled: false, + TelegramBotToken: "bot123", + TelegramChatID: "chat456", + }, + }, + } + if err := notifier.SendTestNotification(context.Background(), ""); err != nil { + t.Fatalf("SendTestNotification returned error: %v", err) + } + if gotRequest == nil { + t.Fatal("expected telegram request to be sent") + } + if got := gotRequest.URL.String(); got != "https://api.telegram.org/botbot123/sendMessage" { + t.Fatalf("request url = %q, want telegram sendMessage endpoint", got) + } + values, err := url.ParseQuery(gotBody) + if err != nil { + t.Fatalf("failed to parse form body: %v", err) + } + if got := values.Get("chat_id"); got != "chat456" { + t.Fatalf("chat_id = %q, want chat456", got) + } + if got := values.Get("text"); !strings.Contains(got, "KlipperAnywhere test notification") { + t.Fatalf("text = %q, want test notification message", got) + } +} + +func TestTelegramNotifierSendPhoto(t *testing.T) { + var gotRequest *http.Request + var gotContentType string + var gotBody []byte + notifier := &telegramNotifier{ + client: &http.Client{ + Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) { + gotRequest = req + gotContentType = req.Header.Get("Content-Type") + body, _ := io.ReadAll(req.Body) + gotBody = append([]byte(nil), body...) + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), + Header: make(http.Header), + Request: req, + }, nil + }), + }, + } + snapshot := []byte{0x01, 0x02, 0x03, 0x04} + if err := notifier.sendTelegramPhoto(context.Background(), "bot123", "chat456", "Print started", snapshot, "snapshot.jpg"); err != nil { + t.Fatalf("sendTelegramPhoto returned error: %v", err) + } + if gotRequest == nil { + t.Fatal("expected telegram request to be sent") + } + if got := gotRequest.URL.String(); got != "https://api.telegram.org/botbot123/sendPhoto" { + t.Fatalf("request url = %q, want telegram sendPhoto endpoint", got) + } + if !strings.HasPrefix(gotContentType, "multipart/form-data; boundary=") { + t.Fatalf("content-type = %q, want multipart form", gotContentType) + } + mr := multipart.NewReader(bytes.NewReader(gotBody), strings.TrimPrefix(gotContentType, "multipart/form-data; boundary=")) + fields := map[string]string{} + var photoName string + var photoBody []byte + for { + part, err := mr.NextPart() + if err == io.EOF { + break + } + if err != nil { + t.Fatalf("failed to parse multipart body: %v", err) + } + data, err := io.ReadAll(part) + if err != nil { + t.Fatalf("failed to read multipart part: %v", err) + } + switch part.FormName() { + case "chat_id", "caption": + fields[part.FormName()] = string(data) + case "photo": + photoName = part.FileName() + photoBody = append([]byte(nil), data...) + } + } + if got := fields["chat_id"]; got != "chat456" { + t.Fatalf("chat_id = %q, want chat456", got) + } + if got := fields["caption"]; got != "Print started" { + t.Fatalf("caption = %q, want Print started", got) + } + if photoName != "snapshot.jpg" { + t.Fatalf("photo filename = %q, want snapshot.jpg", photoName) + } + if !bytes.Equal(photoBody, snapshot) { + t.Fatalf("photo body = %x, want %x", photoBody, snapshot) + } +} + +func TestTelegramNotifierAddsCheckInButton(t *testing.T) { + var gotRequest *http.Request + var gotBody string + notifier := &telegramNotifier{ + client: &http.Client{ + Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) { + gotRequest = req + body, _ := io.ReadAll(req.Body) + gotBody = string(body) + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), + Header: make(http.Header), + Request: req, + }, nil + }), + }, + settings: ¬ificationSettingsStore{ + record: notificationSettingsRecord{ + TelegramEnabled: true, + TelegramBotToken: "bot123", + TelegramChatID: "chat456", + }, + }, + } + record := printerSettingsRecord{ + PrinterID: "Rockchip", + Install: &printerInstallRecord{ + ServerURL: "wss://services.example.com/agent/tunnel", + }, + } + health := &protocol.Health{ + PrintStatus: &protocol.PrintStatus{ + State: "printing", + Filename: "benchy.gcode", + }, + } + if err := notifier.NotifyPrinterPrintStatus(context.Background(), "Rockchip", record, health, nil, ""); err != nil { + t.Fatalf("NotifyPrinterPrintStatus returned error: %v", err) + } + if gotRequest == nil { + t.Fatal("expected telegram request to be sent") + } + if got := gotRequest.URL.String(); got != "https://api.telegram.org/botbot123/sendMessage" { + t.Fatalf("request url = %q, want telegram sendMessage endpoint", got) + } + values, err := url.ParseQuery(gotBody) + if err != nil { + t.Fatalf("failed to parse form body: %v", err) + } + replyMarkup := values.Get("reply_markup") + if replyMarkup == "" { + t.Fatal("expected reply_markup to be present") + } + if !strings.Contains(replyMarkup, `"text":"Printer overview"`) { + t.Fatalf("reply_markup = %q, want Printer overview button", replyMarkup) + } + if !strings.Contains(replyMarkup, "https://services.example.com/printers/Rockchip") { + t.Fatalf("reply_markup = %q, want printer overview url", replyMarkup) + } +} + +func TestTelegramNotifierDeleteMessage(t *testing.T) { + var gotRequest *http.Request + var gotBody string + notifier := &telegramNotifier{ + client: &http.Client{ + Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) { + gotRequest = req + body, _ := io.ReadAll(req.Body) + gotBody = string(body) + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), + Header: make(http.Header), + Request: req, + }, nil + }), + }, + } + if err := notifier.deleteTelegramMessage(context.Background(), "bot123", "chat456", 99); err != nil { + t.Fatalf("deleteTelegramMessage returned error: %v", err) + } + if gotRequest == nil { + t.Fatal("expected telegram request to be sent") + } + if got := gotRequest.URL.String(); got != "https://api.telegram.org/botbot123/deleteMessage" { + t.Fatalf("request url = %q, want deleteMessage endpoint", got) + } + values, err := url.ParseQuery(gotBody) + if err != nil { + t.Fatalf("failed to parse form body: %v", err) + } + if got := values.Get("chat_id"); got != "chat456" { + t.Fatalf("chat_id = %q, want chat456", got) + } + if got := values.Get("message_id"); got != "99" { + t.Fatalf("message_id = %q, want 99", got) + } +} + +func TestTelegramNotifierSetCommandMenu(t *testing.T) { + var gotRequest *http.Request + var gotBody string + notifier := &telegramNotifier{ + client: &http.Client{ + Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) { + gotRequest = req + body, _ := io.ReadAll(req.Body) + gotBody = string(body) + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), + Header: make(http.Header), + Request: req, + }, nil + }), + }, + } + if err := notifier.setTelegramCommandMenu(context.Background(), "bot123", telegramCommandMenu()); err != nil { + t.Fatalf("setTelegramCommandMenu returned error: %v", err) + } + if gotRequest == nil { + t.Fatal("expected telegram request to be sent") + } + if got := gotRequest.URL.String(); got != "https://api.telegram.org/botbot123/setMyCommands" { + t.Fatalf("request url = %q, want setMyCommands endpoint", got) + } + if !strings.Contains(gotBody, `"commands"`) || !strings.Contains(gotBody, `"print"`) || !strings.Contains(gotBody, `"camera"`) || !strings.Contains(gotBody, `"set"`) || !strings.Contains(gotBody, `"all_private_chats"`) { + t.Fatalf("command menu payload missing expected commands: %s", gotBody) + } +} + +func TestPrinterLayerNotificationEvent(t *testing.T) { + if got := printerLayerNotificationEvents(0, 2, "printing"); len(got) != 1 || got[0] != "first_layer" { + t.Fatalf("first layer events = %v, want [first_layer]", got) + } + if got := printerLayerNotificationEvents(2, 4, "printing"); len(got) != 1 || got[0] != "third_layer" { + t.Fatalf("third layer events = %v, want [third_layer]", got) + } + if got := printerLayerNotificationEvents(0, 4, "printing"); len(got) != 2 || got[0] != "first_layer" || got[1] != "third_layer" { + t.Fatalf("crossing events = %v, want [first_layer third_layer]", got) + } + if got := printerLayerNotificationEvents(1, 3, "paused"); len(got) != 0 { + t.Fatalf("paused layer events = %v, want empty", got) + } + if got := printerLayerNotificationEvents(3, 1, "printing"); len(got) != 0 { + t.Fatalf("layer reset events = %v, want empty", got) + } +} + +func TestPrinterLayerNotificationEventsForStatusRequiresTrustedLayerSource(t *testing.T) { + metadataOnly := &protocol.PrintStatus{ + State: "printing", + CurrentLayer: 4, + TotalLayer: 100, + Filename: "benchy.gcode", + LayerSource: "metadata", + } + if got := printerLayerNotificationEventsForStatus(0, metadataOnly); len(got) != 0 { + t.Fatalf("metadata-only layer events = %v, want empty", got) + } + if printerLayerNotificationsTrusted(metadataOnly) { + t.Fatal("metadata-only layer source should not be trusted for notifications") + } + + printStats := &protocol.PrintStatus{ + State: "printing", + CurrentLayer: 4, + LayerSource: "print_stats+metadata", + } + if got := printerLayerNotificationEventsForStatus(0, printStats); len(got) != 2 || got[0] != "first_layer" || got[1] != "third_layer" { + t.Fatalf("print_stats layer events = %v, want [first_layer third_layer]", got) + } + if !printerLayerNotificationsTrusted(printStats) { + t.Fatal("print_stats layer source should be trusted for notifications") + } +} + +func TestShouldPersistPrinterLayerObservationSkipsPrintingZeroLayer(t *testing.T) { + if shouldPersistPrinterLayerObservation(&protocol.PrintStatus{State: "printing", CurrentLayer: 0}) { + t.Fatal("printing zero-layer status should not reset layer observation") + } + if !shouldPersistPrinterLayerObservation(&protocol.PrintStatus{State: "printing", CurrentLayer: 5, LayerSource: "print_stats"}) { + t.Fatal("trusted nonzero printing layer should be persisted") + } + if !shouldPersistPrinterLayerObservation(&protocol.PrintStatus{State: "complete", CurrentLayer: 0}) { + t.Fatal("non-printing zero-layer status should be allowed to reset observation") + } + if shouldPersistPrinterLayerObservation(&protocol.PrintStatus{State: "printing", CurrentLayer: 5, LayerSource: "metadata"}) { + t.Fatal("untrusted layer source should not be persisted") + } +} + +func TestTelegramNotifierBuildLayerMessage(t *testing.T) { + msg := buildTelegramLayerMessage("real-printer", printerSettingsRecord{DisplayName: "Workshop"}, &protocol.Health{ + PrintStatus: &protocol.PrintStatus{ + State: "printing", + Filename: "benchy.gcode", + CurrentLayer: 3, + TotalLayer: 4, + Progress: 0.42, + PrintDuration: 1234, + EstimatedTimeRemaining: 456, + Message: "Layer change", + }, + }, "third_layer") + if !strings.Contains(msg, "Printer: Workshop") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Event: Third layer completed") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "State: printing") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Layer: 3") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Total layers: 4") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Printed:") || !strings.Contains(msg, "Remaining:") { + t.Fatalf("message = %q", msg) + } +} + +func TestTelegramNotifierBuildPrintStatusMessageUsesTotalLayerOnStart(t *testing.T) { + msg := buildTelegramPrintStatusMessage("real-printer", printerSettingsRecord{DisplayName: "Workshop"}, &protocol.Health{ + PrintStatus: &protocol.PrintStatus{ + State: "printing", + Filename: "benchy.gcode", + CurrentLayer: 1, + TotalLayer: 4, + Progress: 0.11, + Message: "Printing benchy", + }, + }) + if !strings.Contains(msg, "Printer: Workshop") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Event: Print started") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "State: printing") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "File: benchy.gcode") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Total layers: 4") { + t.Fatalf("message = %q", msg) + } + if strings.Contains(msg, "Layer: 1/4") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Progress: 11%") { + t.Fatalf("message = %q", msg) + } +} + +func TestParseTelegramCommand(t *testing.T) { + command, args := parseTelegramCommand("/status Rockchip") + if command != "status" || args != "Rockchip" { + t.Fatalf("command=%q args=%q, want status/Rockchip", command, args) + } + if command, args := parseTelegramCommand("hello"); command != "" || args != "" { + t.Fatalf("expected non-command input to be ignored, got %q/%q", command, args) + } +} + +func TestTelegramBotBuildMessages(t *testing.T) { + store := &printerSettingsStore{ + records: map[string]printerSettingsRecord{ + "Rockchip": { + PrinterID: "Rockchip", + DisplayName: "Workshop", + }, + }, + } + bot := &telegramBot{ + server: &server{ + printerSettings: store, + tunnels: map[string]*tunnel{ + "Rockchip": { + health: &protocol.Health{ + PrintStatus: &protocol.PrintStatus{ + State: "printing", + Filename: "benchy.gcode", + CurrentLayer: 3, + TotalLayer: 4, + Progress: 0.42, + }, + }, + }, + }, + }, + } + printers := bot.buildPrintersMessage() + if !strings.Contains(printers, "Workshop (Rockchip)") { + t.Fatalf("printers = %q", printers) + } + if !strings.Contains(printers, "printing, layer 3/4") { + t.Fatalf("printers = %q", printers) + } + status := bot.buildPrinterStatusMessage(telegramPrinterTarget{ + record: printerSettingsRecord{PrinterID: "Rockchip", DisplayName: "Workshop"}, + health: &protocol.Health{ + PrintStatus: &protocol.PrintStatus{ + State: "printing", + Filename: "benchy.gcode", + CurrentLayer: 3, + TotalLayer: 4, + Progress: 0.42, + }, + }, + }) + if !strings.Contains(status, "Printer: Workshop") || !strings.Contains(status, "Layer: 3/4") { + t.Fatalf("status = %q", status) + } + + detailed := bot.buildPrinterStatusMessageWithLiveData(telegramPrinterTarget{ + record: printerSettingsRecord{PrinterID: "Rockchip", DisplayName: "Workshop"}, + health: &protocol.Health{ + PrintStatus: &protocol.PrintStatus{ + State: "printing", + Filename: "benchy.gcode", + CurrentLayer: 3, + TotalLayer: 4, + Progress: 0.42, + }, + }, + }, map[string]any{ + "extruder": map[string]any{"temperature": 215.4, "target": 220.0}, + "fan": map[string]any{"speed": 0.5}, + "display_status": map[string]any{"progress": 0.42}, + }) + if !strings.Contains(detailed, "Temperatures:") || !strings.Contains(detailed, "Fans:") { + t.Fatalf("detailed status = %q", detailed) + } + if !strings.Contains(detailed, "extruder") || !strings.Contains(detailed, "fan") { + t.Fatalf("detailed status = %q", detailed) + } +} + +func TestSelectLastPrintableJob(t *testing.T) { + jobs := []map[string]any{ + {"filename": "active.gcode", "status": "printing"}, + {"filename": "cancelled.gcode", "status": "cancelled"}, + {"filename": "completed.gcode", "status": "completed"}, + } + filename, status := selectLastPrintableJob(jobs) + if filename != "cancelled.gcode" || status != "cancelled" { + t.Fatalf("filename=%q status=%q, want cancelled.gcode/cancelled", filename, status) + } + if !isTerminalJobHistoryStatus("completed") || !isTerminalJobHistoryStatus("canceled") { + t.Fatal("expected terminal history statuses to be recognized") + } + if isTerminalJobHistoryStatus("printing") { + t.Fatal("printing should not be treated as terminal history status") + } +} + +func TestSelectPrintableJobs(t *testing.T) { + jobs := []map[string]any{ + {"filename": "active.gcode", "status": "printing"}, + {"filename": "first.gcode", "status": "completed"}, + {"filename": "second.gcode", "status": "cancelled"}, + {"filename": "third.gcode", "status": "completed"}, + } + selected := selectPrintableJobs(jobs, 2) + if len(selected) != 2 { + t.Fatalf("len(selected) = %d, want 2", len(selected)) + } + if selected[0].Filename != "first.gcode" || selected[1].Filename != "second.gcode" { + t.Fatalf("selected = %+v", selected) + } + if selected[0].ButtonLabel == "" || selected[1].ButtonLabel == "" { + t.Fatalf("button labels should not be empty: %+v", selected) + } +} + +func TestBuildJobHistoryLines(t *testing.T) { + lines := buildJobHistoryLines("Printer: Workshop", []map[string]any{ + {"filename": "first.gcode", "status": "completed"}, + {"filename": "second.gcode"}, + }) + if len(lines) != 4 { + t.Fatalf("len(lines) = %d, want 4", len(lines)) + } + if !strings.Contains(lines[2], "first.gcode (completed)") || !strings.Contains(lines[3], "second.gcode") { + t.Fatalf("unexpected lines: %+v", lines) + } +} + +func TestTelegramBotPrintCancelDeletesConfirmationMessage(t *testing.T) { + var gotURLs []string + var gotBodies []string + notifier := &telegramNotifier{ + client: &http.Client{ + Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) { + gotURLs = append(gotURLs, req.URL.String()) + body, _ := io.ReadAll(req.Body) + gotBodies = append(gotBodies, string(body)) + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), + Header: make(http.Header), + Request: req, + }, nil + }), + }, + } + bot := &telegramBot{ + server: &server{notifier: notifier}, + selections: map[string]telegramPrintSelection{ + "sel": { + PrinterID: "Rockchip", + Filename: "benchy.gcode", + Label: "benchy.gcode", + CreatedAt: time.Now().UTC(), + }, + }, + } + query := &telegramCallbackQuery{ + ID: "cb1", + Data: "cancel:sel", + Message: &telegramMessage{ + MessageID: 99, + Chat: telegramChat{ID: 456}, + }, + } + if err := bot.handleCallbackQuery(context.Background(), "bot123", "456", query); err != nil { + t.Fatalf("handleCallbackQuery returned error: %v", err) + } + if len(gotURLs) == 0 { + t.Fatal("expected telegram requests to be sent") + } + deleteIndex := -1 + for i, gotURL := range gotURLs { + if gotURL == "https://api.telegram.org/botbot123/deleteMessage" { + deleteIndex = i + break + } + } + if deleteIndex == -1 { + t.Fatalf("deleteMessage request not sent: %+v", gotURLs) + } + values, err := url.ParseQuery(gotBodies[deleteIndex]) + if err != nil { + t.Fatalf("failed to parse deleteMessage body: %v", err) + } + if got := values.Get("message_id"); got != "99" { + t.Fatalf("message_id = %q, want 99", got) + } +} + +func TestSelectPrintableFiles(t *testing.T) { + files := []moonrakerFileInfo{ + {Path: "active.gcode", Modified: 100}, + {Path: "older.gcode", Modified: 50}, + {Path: "newer.gcode", Modified: 150}, + } + selected := selectPrintableFiles(files, 2) + if len(selected) != 2 { + t.Fatalf("len(selected) = %d, want 2", len(selected)) + } + if selected[0].Path != "newer.gcode" || selected[1].Path != "active.gcode" { + t.Fatalf("selected = %+v", selected) + } + if selected[0].ButtonLabel == "" || selected[1].ButtonLabel == "" { + t.Fatalf("button labels should not be empty: %+v", selected) + } +} + +func TestTemperatureObjectSummary(t *testing.T) { + lines := temperatureObjectSummary(map[string]any{ + "extruder": map[string]any{"temperature": 215.4, "target": 220.0}, + "heater_bed": map[string]any{"temperature": 60.0}, + "toolhead": map[string]any{"position": []float64{0, 0, 0}}, + }) + if len(lines) != 2 { + t.Fatalf("len(lines) = %d, want 2", len(lines)) + } + if !strings.Contains(lines[0], "\u00b0C") || !strings.Contains(lines[1], "heater_bed") { + t.Fatalf("unexpected temperature lines: %+v", lines) + } +} + +func TestFanObjectSummary(t *testing.T) { + lines := fanObjectSummary(map[string]any{ + "fan": map[string]any{"speed": 0.5}, + "fan_generic part_cooling": map[string]any{"speed": 0.25, "rpm": 1200.0}, + }) + if len(lines) != 2 { + t.Fatalf("len(lines) = %d, want 2", len(lines)) + } + if !strings.Contains(lines[0], "%") || !strings.Contains(lines[1], "rpm") { + t.Fatalf("unexpected fan lines: %+v", lines) + } +} + +func TestParseTelegramCallbackAction(t *testing.T) { + action := parseTelegramCallbackAction("select:abc123") + if action.Kind != "select" || action.ID != "abc123" { + t.Fatalf("action = %+v", action) + } + action = parseTelegramCallbackAction("status:rockchip%2Fmain") + if action.Kind != "status" || action.ID != "rockchip/main" { + t.Fatalf("escaped action = %+v", action) + } + action = parseTelegramCallbackAction("print:rockchip") + if action.Kind != "print" || action.ID != "rockchip" { + t.Fatalf("print action = %+v", action) + } + action = parseTelegramCallbackAction("reprint:rockchip") + if action.Kind != "reprint" || action.ID != "rockchip" { + t.Fatalf("reprint action = %+v", action) + } + action = parseTelegramCallbackAction("camera:rockchip") + if action.Kind != "camera" || action.ID != "rockchip" { + t.Fatalf("camera action = %+v", action) + } + action = parseTelegramCallbackAction("camera-shot:abc123") + if action.Kind != "camera-shot" || action.ID != "abc123" { + t.Fatalf("camera-shot action = %+v", action) + } + action = parseTelegramCallbackAction("jobs:rockchip") + if action.Kind != "jobs" || action.ID != "rockchip" { + t.Fatalf("jobs action = %+v", action) + } + action = parseTelegramCallbackAction("set-temp:abc123:rockchip") + if action.Kind != "set-temp" || action.ID != "abc123:rockchip" { + t.Fatalf("set-temp action = %+v", action) + } + action = parseTelegramCallbackAction("temp-confirm:xyz") + if action.Kind != "temp-confirm" || action.ID != "xyz" { + t.Fatalf("temp-confirm action = %+v", action) + } + action = parseTelegramCallbackAction("temp-cancel:xyz") + if action.Kind != "temp-cancel" || action.ID != "xyz" { + t.Fatalf("temp-cancel action = %+v", action) + } + action = parseTelegramCallbackAction("confirm:xyz") + if action.Kind != "confirm" || action.ID != "xyz" { + t.Fatalf("action = %+v", action) + } + if got := parseTelegramCallbackAction("bogus"); got.Kind != "" || got.ID != "" { + t.Fatalf("unexpected action = %+v", got) + } +} + +func TestPrinterSelectionRecordsIncludesConnectedUnknownPrinters(t *testing.T) { + bot := &telegramBot{ + server: &server{ + printerSettings: &printerSettingsStore{ + records: map[string]printerSettingsRecord{ + "saved": { + PrinterID: "saved", + DisplayName: "Saved Printer", + }, + }, + }, + tunnels: map[string]*tunnel{ + "saved": {}, + "connected-only": {}, + }, + }, + } + records := bot.printerSelectionRecords() + if len(records) != 2 { + t.Fatalf("len(records) = %d, want 2", len(records)) + } + if records[0].PrinterID != "connected-only" || records[1].PrinterID != "saved" { + t.Fatalf("records = %+v", records) + } +} + +func TestBuildPrintConfirmationMessage(t *testing.T) { + bot := &telegramBot{} + msg := bot.buildPrintConfirmationMessage( + telegramPrinterTarget{ + record: printerSettingsRecord{PrinterID: "Rockchip", DisplayName: "Workshop"}, + health: &protocol.Health{ + PrintStatus: &protocol.PrintStatus{State: "idle"}, + }, + }, + telegramPrintSelection{PrinterID: "Rockchip", Filename: "benchy.gcode", Label: "benchy.gcode (completed)"}, + "select", + ) + if !strings.Contains(msg, "Printer: Workshop") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Action: Start print") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "File: benchy.gcode") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Selection: benchy.gcode (completed)") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Snapshot: review the bed before confirming") { + t.Fatalf("message = %q", msg) + } +} + +func TestBuildReprintConfirmationMessage(t *testing.T) { + bot := &telegramBot{} + msg := bot.buildReprintConfirmationMessage( + telegramPrinterTarget{ + record: printerSettingsRecord{PrinterID: "Rockchip", DisplayName: "Workshop"}, + health: &protocol.Health{ + PrintStatus: &protocol.PrintStatus{State: "idle"}, + }, + }, + telegramPrintSelection{PrinterID: "Rockchip", Filename: "benchy.gcode", Label: "benchy.gcode (completed)"}, + ) + if !strings.Contains(msg, "Action: Reprint last job") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Snapshot: review the bed before confirming") { + t.Fatalf("message = %q", msg) + } +} + +func TestBuildTemperatureConfirmationMessage(t *testing.T) { + bot := &telegramBot{} + msg := bot.buildTemperatureConfirmationMessage( + telegramPrinterTarget{ + record: printerSettingsRecord{PrinterID: "Rockchip", DisplayName: "Workshop"}, + health: &protocol.Health{ + PrintStatus: &protocol.PrintStatus{State: "printing"}, + }, + }, + telegramTemperatureSelection{ + Heater: "heater_bed", + Target: 60, + }, + ) + if !strings.Contains(msg, "Printer: Workshop") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Action: Set bed target") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Target: bed 60.0\u00b0C") { + t.Fatalf("message = %q", msg) + } + if !strings.Contains(msg, "Snapshot: review the bed before confirming") { + t.Fatalf("message = %q", msg) + } +} +func TestTelegramHelpMessageIncludesNewCommands(t *testing.T) { + msg := telegramHelpMessage() + for _, want := range []string{"/jobs", "/camera", "/status", "/set"} { + if !strings.Contains(msg, want) { + t.Fatalf("help message missing %q: %s", want, msg) + } + } + for _, unwanted := range []string{"/temps", "/fans", "/snapshot"} { + if strings.Contains(msg, unwanted) { + t.Fatalf("help message should not include %q: %s", unwanted, msg) + } + } +} + +func TestParseTelegramTemperatureSetArgs(t *testing.T) { + printer, heater, target, err := parseTelegramTemperatureSetArgs("extruder 215") + if err != nil { + t.Fatalf("parseTelegramTemperatureSetArgs returned error: %v", err) + } + if printer != "" || heater != "extruder" || target != 215 { + t.Fatalf("parsed args = %q %q %v", printer, heater, target) + } + printer, heater, target, err = parseTelegramTemperatureSetArgs("Rockchip bed 60") + if err != nil { + t.Fatalf("parseTelegramTemperatureSetArgs returned error: %v", err) + } + if printer != "Rockchip" || heater != "heater_bed" || target != 60 { + t.Fatalf("parsed args = %q %q %v", printer, heater, target) + } + if _, _, _, err := parseTelegramTemperatureSetArgs("something 60"); err == nil { + t.Fatal("expected unknown heater to fail") + } +} + +func TestNormalizeTemperatureHeater(t *testing.T) { + tests := map[string]string{ + "extruder": "extruder", + "nozzle": "extruder", + "bed": "heater_bed", + "heatedbed": "heater_bed", + "heater_bed": "heater_bed", + } + for input, want := range tests { + got, err := normalizeTemperatureHeater(input) + if err != nil { + t.Fatalf("normalizeTemperatureHeater(%q) returned error: %v", input, err) + } + if got != want { + t.Fatalf("normalizeTemperatureHeater(%q) = %q, want %q", input, got, want) + } + } + if _, err := normalizeTemperatureHeater("side"); err == nil { + t.Fatal("expected unknown heater to fail") + } +} + +func TestSnapshotCapableCameras(t *testing.T) { + health := &protocol.Health{Cameras: []protocol.CameraHealth{ + {Name: "wide", HasSnapshot: true}, + {Name: "stream-only", HasSnapshot: false, HasStream: true}, + {Name: "nozzle", HasSnapshot: true}, + }} + cameras := snapshotCapableCameras(health) + if len(cameras) != 2 { + t.Fatalf("len(cameras) = %d, want 2", len(cameras)) + } + if cameras[0].Name != "nozzle" || cameras[1].Name != "wide" { + t.Fatalf("cameras = %+v", cameras) + } +} + + diff --git a/cmd/server/notification_settings.go b/cmd/server/notification_settings.go new file mode 100644 index 0000000..3e2fad5 --- /dev/null +++ b/cmd/server/notification_settings.go @@ -0,0 +1,128 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +type notificationSettingsStore struct { + path string + mu sync.RWMutex + record notificationSettingsRecord +} + +type notificationSettingsRecord struct { + TelegramEnabled bool `json:"telegram_enabled,omitempty"` + TelegramCommandsEnabled bool `json:"telegram_commands_enabled,omitempty"` + TelegramBotToken string `json:"telegram_bot_token,omitempty"` + TelegramChatID string `json:"telegram_chat_id,omitempty"` + UpdatedAt time.Time `json:"updated_at"` +} + +func newNotificationSettingsStore(path string) (*notificationSettingsStore, error) { + store := ¬ificationSettingsStore{path: path} + if err := store.loadLocked(); err != nil { + return nil, err + } + return store, nil +} + +func (s *notificationSettingsStore) loadLocked() error { + if s == nil || s.path == "" { + return nil + } + data, err := os.ReadFile(s.path) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + if len(strings.TrimSpace(string(data))) == 0 { + return nil + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(data, &raw); err != nil { + return fmt.Errorf("failed to parse notification settings file: %w", err) + } + var record notificationSettingsRecord + if err := json.Unmarshal(data, &record); err != nil { + return fmt.Errorf("failed to parse notification settings file: %w", err) + } + if _, ok := raw["telegram_commands_enabled"]; !ok { + record.TelegramCommandsEnabled = record.TelegramEnabled + } + s.record = record + return nil +} + +func (s *notificationSettingsStore) saveLocked() error { + if s == nil || s.path == "" { + return nil + } + if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil { + return err + } + encoded, err := json.MarshalIndent(s.record, "", " ") + if err != nil { + return err + } + encoded = append(encoded, '\n') + return os.WriteFile(s.path, encoded, 0o600) +} + +func (s *notificationSettingsStore) snapshot() notificationSettingsRecord { + if s == nil { + return notificationSettingsRecord{} + } + s.mu.RLock() + defer s.mu.RUnlock() + return s.record +} + +func (s *notificationSettingsStore) update(telegramEnabled *bool, telegramCommandsEnabled *bool, telegramBotToken *string, telegramChatID *string) (notificationSettingsRecord, error) { + if s == nil { + return notificationSettingsRecord{}, nil + } + s.mu.Lock() + defer s.mu.Unlock() + + if telegramEnabled != nil { + s.record.TelegramEnabled = *telegramEnabled + } + if telegramCommandsEnabled != nil { + s.record.TelegramCommandsEnabled = *telegramCommandsEnabled + } + if telegramBotToken != nil { + s.record.TelegramBotToken = strings.TrimSpace(*telegramBotToken) + } + if telegramChatID != nil { + s.record.TelegramChatID = strings.TrimSpace(*telegramChatID) + } + s.record.UpdatedAt = time.Now().UTC() + if err := s.saveLocked(); err != nil { + return notificationSettingsRecord{}, err + } + return s.record, nil +} + +func (s *notificationSettingsStore) configured() bool { + record := s.snapshot() + return strings.TrimSpace(record.TelegramBotToken) != "" && strings.TrimSpace(record.TelegramChatID) != "" +} + +func publicNotificationSettings(record notificationSettingsRecord) map[string]any { + return map[string]any{ + "telegram_enabled": record.TelegramEnabled, + "telegram_commands_enabled": record.TelegramCommandsEnabled, + "telegram_bot_token": record.TelegramBotToken, + "telegram_bot_token_set": strings.TrimSpace(record.TelegramBotToken) != "", + "telegram_chat_id": record.TelegramChatID, + "updated_at": record.UpdatedAt, + } +} diff --git a/cmd/server/notifications.go b/cmd/server/notifications.go new file mode 100644 index 0000000..c1f09ea --- /dev/null +++ b/cmd/server/notifications.go @@ -0,0 +1,540 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log" + "mime/multipart" + "net/http" + "net/url" + "strings" + "time" + + "github.com/klipperanywhere/klipperanywhere/internal/protocol" +) + +type telegramNotifier struct { + client *http.Client + settings *notificationSettingsStore +} + +type telegramBotCommandScope struct { + Type string `json:"type"` +} + +type telegramInlineKeyboardMarkup struct { + InlineKeyboard [][]telegramInlineKeyboardButton `json:"inline_keyboard"` +} + +type telegramInlineKeyboardButton struct { + Text string `json:"text"` + URL string `json:"url,omitempty"` +} + +func (n *telegramNotifier) NotifyPrinterPrintStatus(ctx context.Context, printerID string, record printerSettingsRecord, health *protocol.Health, snapshot []byte, snapshotName string) error { + if n == nil || n.client == nil || health == nil || health.PrintStatus == nil { + return nil + } + enabled, token, chatID := n.deliveryCredentials() + if !enabled || token == "" || chatID == "" { + return nil + } + message := buildTelegramPrintStatusMessage(printerID, record, health) + if strings.TrimSpace(message) == "" { + return nil + } + return n.sendTelegramNotification(ctx, token, chatID, message, snapshot, snapshotName, telegramCheckInMarkup(printerID, record)) +} + +func (n *telegramNotifier) NotifyPrinterLayerStatus(ctx context.Context, printerID string, record printerSettingsRecord, health *protocol.Health, layerEvent string, snapshot []byte, snapshotName string) error { + if n == nil || n.client == nil || health == nil || health.PrintStatus == nil { + return nil + } + enabled, token, chatID := n.deliveryCredentials() + if !enabled || token == "" || chatID == "" { + return nil + } + message := buildTelegramLayerMessage(printerID, record, health, layerEvent) + if strings.TrimSpace(message) == "" { + return nil + } + return n.sendTelegramNotification(ctx, token, chatID, message, snapshot, snapshotName, telegramCheckInMarkup(printerID, record)) +} + +func (n *telegramNotifier) SendTestNotification(ctx context.Context, message string) error { + if n == nil || n.client == nil { + return fmt.Errorf("telegram notifier unavailable") + } + _, token, chatID := n.deliveryCredentials() + if token == "" || chatID == "" { + return fmt.Errorf("telegram bot token and chat ID are required") + } + body := strings.TrimSpace(message) + if body == "" { + body = "KlipperAnywhere test notification\nIf you received this, Telegram delivery is working." + } + return n.sendTelegramMessage(ctx, token, chatID, body) +} + +func (n *telegramNotifier) deliveryCredentials() (bool, string, string) { + if n != nil && n.settings != nil { + global := n.settings.snapshot() + token := strings.TrimSpace(global.TelegramBotToken) + chatID := strings.TrimSpace(global.TelegramChatID) + if token != "" && chatID != "" { + return global.TelegramEnabled, token, chatID + } + } + return false, "", "" +} + +func (n *telegramNotifier) sendTelegramMessage(ctx context.Context, token, chatID, message string) error { + return n.sendTelegramMessageWithMarkup(ctx, token, chatID, message, nil) +} + +func (n *telegramNotifier) deleteTelegramMessage(ctx context.Context, token string, chatID string, messageID int64) error { + if n == nil || n.client == nil { + return fmt.Errorf("telegram notifier unavailable") + } + endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/deleteMessage", token) + form := url.Values{} + form.Set("chat_id", chatID) + form.Set("message_id", fmt.Sprintf("%d", messageID)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := n.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + detail := strings.TrimSpace(string(body)) + if detail != "" { + return fmt.Errorf("telegram deleteMessage failed: %s: %s", resp.Status, detail) + } + return fmt.Errorf("telegram deleteMessage failed: %s", resp.Status) + } + return nil +} + +func (n *telegramNotifier) setTelegramCommandMenu(ctx context.Context, token string, commands []telegramBotCommand) error { + if n == nil || n.client == nil { + return fmt.Errorf("telegram notifier unavailable") + } + endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/setMyCommands", token) + body := map[string]any{ + "commands": commands, + "scope": telegramBotCommandScope{ + Type: "all_private_chats", + }, + } + payload, err := json.Marshal(body) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(string(payload))) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + resp, err := n.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + detail := strings.TrimSpace(string(body)) + if detail != "" { + return fmt.Errorf("telegram setMyCommands failed: %s: %s", resp.Status, detail) + } + return fmt.Errorf("telegram setMyCommands failed: %s", resp.Status) + } + return nil +} + +func (n *telegramNotifier) deleteTelegramCommandMenu(ctx context.Context, token string) error { + if n == nil || n.client == nil { + return fmt.Errorf("telegram notifier unavailable") + } + endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/deleteMyCommands", token) + body := map[string]any{ + "scope": telegramBotCommandScope{ + Type: "all_private_chats", + }, + } + payload, err := json.Marshal(body) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(string(payload))) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + resp, err := n.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + detail := strings.TrimSpace(string(body)) + if detail != "" { + return fmt.Errorf("telegram deleteMyCommands failed: %s: %s", resp.Status, detail) + } + return fmt.Errorf("telegram deleteMyCommands failed: %s", resp.Status) + } + return nil +} + +func (n *telegramNotifier) sendTelegramMessageWithMarkup(ctx context.Context, token, chatID, message string, replyMarkup any) error { + if n == nil || n.client == nil { + return fmt.Errorf("telegram notifier unavailable") + } + endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", token) + form := url.Values{} + form.Set("chat_id", chatID) + form.Set("text", message) + form.Set("disable_web_page_preview", "true") + if replyMarkup != nil { + encoded, err := json.Marshal(replyMarkup) + if err != nil { + return err + } + form.Set("reply_markup", string(encoded)) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := n.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + detail := strings.TrimSpace(string(body)) + if detail != "" { + return fmt.Errorf("telegram sendMessage failed: %s: %s", resp.Status, detail) + } + return fmt.Errorf("telegram sendMessage failed: %s", resp.Status) + } + return nil +} + +func (n *telegramNotifier) sendTelegramPhoto(ctx context.Context, token, chatID, caption string, photo []byte, filename string) error { + return n.sendTelegramPhotoWithMarkup(ctx, token, chatID, caption, photo, filename, nil) +} + +func (n *telegramNotifier) sendTelegramPhotoWithMarkup(ctx context.Context, token, chatID, caption string, photo []byte, filename string, replyMarkup any) error { + if n == nil || n.client == nil { + return fmt.Errorf("telegram notifier unavailable") + } + if len(photo) == 0 { + return fmt.Errorf("telegram photo is empty") + } + endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/sendPhoto", token) + body := &bytes.Buffer{} + writer := multipart.NewWriter(body) + if err := writer.WriteField("chat_id", chatID); err != nil { + return err + } + if caption = strings.TrimSpace(caption); caption != "" { + if len([]rune(caption)) > 900 { + runes := []rune(caption) + caption = string(runes[:900]) + "..." + } + if err := writer.WriteField("caption", caption); err != nil { + return err + } + } + if filename == "" { + filename = "snapshot.jpg" + } + part, err := writer.CreateFormFile("photo", filename) + if err != nil { + return err + } + if _, err := part.Write(photo); err != nil { + return err + } + if replyMarkup != nil { + if encoded, err := json.Marshal(replyMarkup); err != nil { + return err + } else if err := writer.WriteField("reply_markup", string(encoded)); err != nil { + return err + } + } + if err := writer.Close(); err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, body) + if err != nil { + return err + } + req.Header.Set("Content-Type", writer.FormDataContentType()) + resp, err := n.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + detail := strings.TrimSpace(string(body)) + if detail != "" { + return fmt.Errorf("telegram sendPhoto failed: %s: %s", resp.Status, detail) + } + return fmt.Errorf("telegram sendPhoto failed: %s", resp.Status) + } + return nil +} + +func (n *telegramNotifier) sendTelegramNotification(ctx context.Context, token, chatID, message string, snapshot []byte, snapshotName string, replyMarkup any) error { + if len(snapshot) > 0 { + if err := n.sendTelegramPhotoWithMarkup(ctx, token, chatID, message, snapshot, snapshotName, replyMarkup); err == nil { + return nil + } else { + log.Printf("telegram photo send failed; falling back to text notification: %v", err) + } + } + return n.sendTelegramMessageWithMarkup(ctx, token, chatID, message, replyMarkup) +} + +func telegramCheckInMarkup(printerID string, record printerSettingsRecord) any { + overviewURL := telegramPrinterOverviewURL(printerID, record) + if overviewURL == "" { + return nil + } + return telegramInlineKeyboardMarkup{ + InlineKeyboard: [][]telegramInlineKeyboardButton{ + { + { + Text: "Printer overview", + URL: overviewURL, + }, + }, + }, + } +} + +func telegramPrinterOverviewURL(printerID string, record printerSettingsRecord) string { + printerID = strings.TrimSpace(printerID) + if printerID == "" { + return "" + } + for _, raw := range telegramPrinterInstallServerURLs(record) { + if overviewURL := derivePrinterOverviewURL(raw, printerID); overviewURL != "" { + return overviewURL + } + } + return "" +} + +func telegramPrinterInstallServerURLs(record printerSettingsRecord) []string { + urls := make([]string, 0, 1+len(record.InstallHistory)) + if record.Install != nil { + urls = append(urls, strings.TrimSpace(record.Install.ServerURL)) + } + for _, install := range record.InstallHistory { + if url := strings.TrimSpace(install.ServerURL); url != "" { + urls = append(urls, url) + } + } + return urls +} + +func derivePrinterOverviewURL(raw string, printerID string) string { + raw = strings.TrimSpace(raw) + printerID = strings.TrimSpace(printerID) + if raw == "" || printerID == "" { + return "" + } + parsed, err := url.Parse(raw) + if err != nil { + return "" + } + switch strings.ToLower(parsed.Scheme) { + case "http", "https": + case "ws": + parsed.Scheme = "http" + case "wss": + parsed.Scheme = "https" + default: + return "" + } + if parsed.Host == "" { + return "" + } + parsed.Fragment = "" + parsed.RawQuery = "" + parsed.Path = strings.TrimSuffix(parsed.Path, "/") + parsed.Path = strings.TrimSuffix(parsed.Path, "/agent/tunnel") + parsed.Path = strings.TrimSuffix(parsed.Path, "/") + parsed.Path = strings.TrimRight(parsed.Path, "/") + parsed.Path = parsed.Path + "/printers/" + url.PathEscape(printerID) + if !strings.HasPrefix(parsed.Path, "/") { + parsed.Path = "/" + parsed.Path + } + return parsed.String() +} + +func buildTelegramPrintStatusMessage(printerID string, record printerSettingsRecord, health *protocol.Health) string { + status := health.PrintStatus + if status == nil { + return "" + } + current := strings.ToLower(strings.TrimSpace(status.State)) + previous := strings.ToLower(strings.TrimSpace(record.LastObservedPrintState)) + label := "Print update" + isStarted := false + switch current { + case "printing": + if previous == "paused" { + label = "Print resumed" + } else { + label = "Print started" + isStarted = true + } + case "paused": + label = "Print paused" + case "complete", "completed": + label = "Print completed" + case "cancelled", "canceled": + label = "Print canceled" + case "error", "failed": + label = "Print failed" + } + printerName := strings.TrimSpace(record.DisplayName) + if printerName == "" { + printerName = printerID + } + lines := []string{ + fmt.Sprintf("Printer: %s", printerName), + fmt.Sprintf("Event: %s", label), + fmt.Sprintf("State: %s", current), + } + if fn := strings.TrimSpace(status.Filename); fn != "" { + lines = append(lines, fmt.Sprintf("File: %s", fn)) + } + if isStarted { + if status.TotalLayer > 0 { + lines = append(lines, fmt.Sprintf("Total layers: %d", status.TotalLayer)) + } + } else if layer := formatTelegramLayer(status.CurrentLayer, status.TotalLayer); layer != "" { + lines = append(lines, fmt.Sprintf("Layer: %s", layer)) + } + if current == "printing" && previous == "paused" { + lines = append(lines, "Reason: print resumed after pause") + } + if progress := status.Progress; progress > 0 { + lines = append(lines, fmt.Sprintf("Progress: %.0f%%", progress*100)) + } + if duration := formatTelegramDuration(status.PrintDuration); duration != "" { + lines = append(lines, fmt.Sprintf("Printed: %s", duration)) + } + if duration := formatTelegramDuration(status.TotalDuration); duration != "" { + lines = append(lines, fmt.Sprintf("Job total: %s", duration)) + } + if remaining := formatTelegramDuration(status.EstimatedTimeRemaining); remaining != "" && current == "printing" { + lines = append(lines, fmt.Sprintf("Remaining: %s", remaining)) + } + if message := strings.TrimSpace(status.Message); message != "" { + lines = append(lines, fmt.Sprintf("Message: %s", message)) + } + return strings.Join(lines, "\n") +} + +func formatTelegramLayer(currentLayer, totalLayer int) string { + if currentLayer <= 0 && totalLayer <= 0 { + return "" + } + if currentLayer > 0 && totalLayer > 0 { + return fmt.Sprintf("%d/%d", currentLayer, totalLayer) + } + if currentLayer > 0 { + return fmt.Sprintf("%d", currentLayer) + } + return fmt.Sprintf("?/%d", totalLayer) +} + +func buildTelegramLayerMessage(printerID string, record printerSettingsRecord, health *protocol.Health, layerEvent string) string { + status := health.PrintStatus + if status == nil { + return "" + } + printerName := strings.TrimSpace(record.DisplayName) + if printerName == "" { + printerName = printerID + } + label := "Layer update" + switch strings.ToLower(strings.TrimSpace(layerEvent)) { + case "first_layer": + label = "First layer completed" + case "third_layer": + label = "Third layer completed" + } + lines := []string{ + fmt.Sprintf("Printer: %s", printerName), + fmt.Sprintf("Event: %s", label), + } + if state := strings.TrimSpace(status.State); state != "" { + lines = append(lines, fmt.Sprintf("State: %s", state)) + } + if fn := strings.TrimSpace(status.Filename); fn != "" { + lines = append(lines, fmt.Sprintf("File: %s", fn)) + } + if status.CurrentLayer > 0 { + lines = append(lines, fmt.Sprintf("Layer: %d", status.CurrentLayer)) + } + if status.TotalLayer > 0 { + lines = append(lines, fmt.Sprintf("Total layers: %d", status.TotalLayer)) + } + if progress := status.Progress; progress > 0 { + lines = append(lines, fmt.Sprintf("Progress: %.0f%%", progress*100)) + } + if duration := formatTelegramDuration(status.PrintDuration); duration != "" { + lines = append(lines, fmt.Sprintf("Printed: %s", duration)) + } + if remaining := formatTelegramDuration(status.EstimatedTimeRemaining); remaining != "" { + lines = append(lines, fmt.Sprintf("Remaining: %s", remaining)) + } + if message := strings.TrimSpace(status.Message); message != "" { + lines = append(lines, fmt.Sprintf("Message: %s", message)) + } + return strings.Join(lines, "\n") +} + +func formatTelegramDuration(seconds float64) string { + if seconds <= 0 { + return "" + } + d := time.Duration(seconds * float64(time.Second)) + if d < time.Minute { + return d.Round(time.Second).String() + } + hours := d / time.Hour + d -= hours * time.Hour + minutes := d / time.Minute + d -= minutes * time.Minute + parts := make([]string, 0, 3) + if hours > 0 { + parts = append(parts, fmt.Sprintf("%dh", hours)) + } + if minutes > 0 { + parts = append(parts, fmt.Sprintf("%dm", minutes)) + } + if d > 0 || len(parts) == 0 { + parts = append(parts, fmt.Sprintf("%ds", d.Round(time.Second)/time.Second)) + } + return strings.Join(parts, " ") +} diff --git a/cmd/server/printer_settings.go b/cmd/server/printer_settings.go new file mode 100644 index 0000000..3866ea7 --- /dev/null +++ b/cmd/server/printer_settings.go @@ -0,0 +1,540 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/klipperanywhere/klipperanywhere/internal/protocol" +) + +type printerSettingsStore struct { + path string + mu sync.RWMutex + records map[string]printerSettingsRecord +} + +type printerSettingsRecord struct { + PrinterID string `json:"printer_id"` + DisplayName string `json:"display_name,omitempty"` + ControlMode string `json:"control_mode"` + UIURL string `json:"ui_url,omitempty"` + UIAutoDetect bool `json:"ui_auto_detect"` + NotificationSnapshotCamera string `json:"notification_snapshot_camera,omitempty"` + PrintNotificationsEnabled bool `json:"print_notifications_enabled,omitempty"` + NotifyPrintStarted bool `json:"notify_print_started,omitempty"` + NotifyPrintPaused bool `json:"notify_print_paused,omitempty"` + NotifyPrintResumed bool `json:"notify_print_resumed,omitempty"` + NotifyPrintCompleted bool `json:"notify_print_completed,omitempty"` + NotifyPrintCanceled bool `json:"notify_print_canceled,omitempty"` + NotifyPrintFailed bool `json:"notify_print_failed,omitempty"` + NotifyFirstLayer bool `json:"notify_print_first_layer,omitempty"` + NotifyThirdLayer bool `json:"notify_print_third_layer,omitempty"` + LastObservedPrintState string `json:"last_observed_print_state,omitempty"` + LastObservedPrintFile string `json:"last_observed_print_file,omitempty"` + LastObservedPrintLayer int `json:"last_observed_print_layer,omitempty"` + LastObservedAt time.Time `json:"last_observed_at,omitempty"` + LastNotifiedPrintState string `json:"last_notified_print_state,omitempty"` + LastNotifiedPrintFile string `json:"last_notified_print_file,omitempty"` + LastNotifiedAt time.Time `json:"last_notified_at,omitempty"` + LastNotificationSource string `json:"last_notification_source,omitempty"` + LastNotificationError string `json:"last_notification_error,omitempty"` + LastLayerNotifiedPrintLayer int `json:"last_layer_notified_print_layer,omitempty"` + LastLayerNotifiedAt time.Time `json:"last_layer_notified_at,omitempty"` + LastLayerNotificationSource string `json:"last_layer_notification_source,omitempty"` + LastLayerNotificationError string `json:"last_layer_notification_error,omitempty"` + UpdatedAt time.Time `json:"updated_at"` + DisplayNameUpdatedAt time.Time `json:"display_name_updated_at,omitempty"` + LastSyncedAt time.Time `json:"last_synced_at,omitempty"` + Install *printerInstallRecord `json:"install,omitempty"` + InstallHistory []printerInstallRecord `json:"install_history,omitempty"` +} + +type printerInstallRecord struct { + Host string `json:"host,omitempty"` + Port int `json:"port,omitempty"` + Username string `json:"username,omitempty"` + HostType string `json:"host_type,omitempty"` + ServerURL string `json:"server_url,omitempty"` + PrinterID string `json:"printer_id,omitempty"` + MoonrakerURL string `json:"moonraker_url,omitempty"` + UIURL string `json:"ui_url,omitempty"` + UIAutoDetect bool `json:"ui_auto_detect"` + RequestedBy string `json:"requested_by,omitempty"` + RemoteHost string `json:"remote_host,omitempty"` + ReleaseURL string `json:"release_url,omitempty"` + BinarySource string `json:"binary_source,omitempty"` + ConfigPath string `json:"config_path,omitempty"` + BinaryPath string `json:"binary_path,omitempty"` + Message string `json:"message,omitempty"` + PostInstallConnected bool `json:"post_install_connected"` + PostInstallMessage string `json:"post_install_message,omitempty"` + RollbackPerformed bool `json:"rollback_performed"` + RollbackMessage string `json:"rollback_message,omitempty"` + Status string `json:"status,omitempty"` + Error string `json:"error,omitempty"` + UpdatedAt time.Time `json:"updated_at"` +} + +const maxInstallHistoryEntries = 12 + +type printerSettingsFile struct { + Printers []printerSettingsRecord `json:"printers"` +} + +func newPrinterSettingsStore(path string) (*printerSettingsStore, error) { + store := &printerSettingsStore{ + path: path, + records: make(map[string]printerSettingsRecord), + } + if err := store.loadLocked(); err != nil { + return nil, err + } + return store, nil +} + +func newDefaultPrinterSettingsRecord(printerID string, defaultControlMode string) printerSettingsRecord { + record := printerSettingsRecord{ + PrinterID: printerID, + ControlMode: normalizeControlMode(defaultControlMode), + UIAutoDetect: true, + PrintNotificationsEnabled: true, + NotifyPrintStarted: true, + NotifyPrintPaused: true, + NotifyPrintResumed: true, + NotifyPrintCompleted: true, + NotifyPrintCanceled: true, + NotifyPrintFailed: true, + NotifyFirstLayer: false, + NotifyThirdLayer: false, + } + if record.ControlMode == "" { + record.ControlMode = "readonly" + } + return record +} + +func (s *printerSettingsStore) loadLocked() error { + if s.path == "" { + return nil + } + data, err := os.ReadFile(s.path) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + if len(strings.TrimSpace(string(data))) == 0 { + return nil + } + var file printerSettingsFile + if err := json.Unmarshal(data, &file); err != nil { + return fmt.Errorf("failed to parse printer settings file: %w", err) + } + s.records = make(map[string]printerSettingsRecord, len(file.Printers)) + for _, record := range file.Printers { + if record.PrinterID == "" { + continue + } + record.ControlMode = normalizeControlMode(record.ControlMode) + if record.ControlMode == "" { + record.ControlMode = "readonly" + } + if !record.PrintNotificationsEnabled && !record.NotifyPrintStarted && !record.NotifyPrintPaused && !record.NotifyPrintResumed && !record.NotifyPrintCompleted && !record.NotifyPrintCanceled && !record.NotifyPrintFailed { + record.PrintNotificationsEnabled = true + record.NotifyPrintStarted = true + record.NotifyPrintPaused = true + record.NotifyPrintResumed = true + record.NotifyPrintCompleted = true + record.NotifyPrintCanceled = true + record.NotifyPrintFailed = true + } + s.records[record.PrinterID] = record + } + return nil +} + +func (s *printerSettingsStore) saveLocked() error { + if s.path == "" { + return nil + } + if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil { + return err + } + file := printerSettingsFile{Printers: make([]printerSettingsRecord, 0, len(s.records))} + for _, record := range s.records { + file.Printers = append(file.Printers, record) + } + sort.Slice(file.Printers, func(i, j int) bool { + return strings.ToLower(file.Printers[i].PrinterID) < strings.ToLower(file.Printers[j].PrinterID) + }) + encoded, err := json.MarshalIndent(file, "", " ") + if err != nil { + return err + } + encoded = append(encoded, '\n') + return os.WriteFile(s.path, encoded, 0o600) +} + +func (s *printerSettingsStore) ensureFromHealth(printerID string, health *protocol.Health, defaultControlMode string) (printerSettingsRecord, bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + + if record, ok := s.records[printerID]; ok { + return record, false, nil + } + record := printerSettingsRecord{ + PrinterID: printerID, + ControlMode: normalizeControlMode(defaultControlMode), + UIAutoDetect: true, + UpdatedAt: time.Now().UTC(), + } + record.PrintNotificationsEnabled = true + record.NotifyPrintStarted = true + record.NotifyPrintPaused = true + record.NotifyPrintResumed = true + record.NotifyPrintCompleted = true + record.NotifyPrintCanceled = true + record.NotifyPrintFailed = true + record.NotifyFirstLayer = false + record.NotifyThirdLayer = false + if record.ControlMode == "" { + record.ControlMode = "readonly" + } + if health != nil { + record.UIURL = strings.TrimSpace(health.UIURL) + record.UIAutoDetect = health.UIAutoDetect + } + s.records[printerID] = record + if err := s.saveLocked(); err != nil { + delete(s.records, printerID) + return printerSettingsRecord{}, false, err + } + return record, true, nil +} + +func (s *printerSettingsStore) snapshot(printerID string) (printerSettingsRecord, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + record, ok := s.records[printerID] + return record, ok +} + +func (s *printerSettingsStore) list() []printerSettingsRecord { + s.mu.RLock() + defer s.mu.RUnlock() + records := make([]printerSettingsRecord, 0, len(s.records)) + for _, record := range s.records { + records = append(records, record) + } + sort.Slice(records, func(i, j int) bool { + return strings.ToLower(records[i].PrinterID) < strings.ToLower(records[j].PrinterID) + }) + return records +} + +func (s *printerSettingsStore) current(printerID string, health *protocol.Health, defaultControlMode string) printerSettingsRecord { + if record, ok := s.snapshot(printerID); ok { + return record + } + record := printerSettingsRecord{ + PrinterID: printerID, + ControlMode: normalizeControlMode(defaultControlMode), + UIAutoDetect: true, + } + record.PrintNotificationsEnabled = true + record.NotifyPrintStarted = true + record.NotifyPrintPaused = true + record.NotifyPrintResumed = true + record.NotifyPrintCompleted = true + record.NotifyPrintCanceled = true + record.NotifyPrintFailed = true + record.NotifyFirstLayer = false + record.NotifyThirdLayer = false + if record.ControlMode == "" { + record.ControlMode = "readonly" + } + if health != nil { + if ui := strings.TrimSpace(health.UIURL); ui != "" { + record.UIURL = ui + } + record.UIAutoDetect = health.UIAutoDetect + } + return record +} + +func (s *printerSettingsStore) update(printerID string, displayName *string, controlMode *string, uiURL *string, uiAutoDetect *bool, notificationSnapshotCamera *string, defaultControlMode string) (printerSettingsRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.records[printerID] + if !ok { + record = newDefaultPrinterSettingsRecord(printerID, defaultControlMode) + } + if displayName != nil { + trimmed := strings.TrimSpace(*displayName) + if record.DisplayName != trimmed { + record.DisplayName = trimmed + record.DisplayNameUpdatedAt = time.Now().UTC() + } + } + if controlMode != nil { + normalized := normalizeControlMode(*controlMode) + if normalized == "" { + return printerSettingsRecord{}, fmt.Errorf("invalid control mode %q", *controlMode) + } + record.ControlMode = normalized + } + if uiURL != nil { + record.UIURL = strings.TrimSpace(*uiURL) + } + if uiAutoDetect != nil { + record.UIAutoDetect = *uiAutoDetect + } + if notificationSnapshotCamera != nil { + record.NotificationSnapshotCamera = strings.TrimSpace(*notificationSnapshotCamera) + } + if record.ControlMode == "" { + record.ControlMode = "readonly" + } + record.UpdatedAt = time.Now().UTC() + s.records[printerID] = record + if err := s.saveLocked(); err != nil { + delete(s.records, printerID) + return printerSettingsRecord{}, err + } + return record, nil +} + +func (s *printerSettingsStore) updateNotifications(printerID string, enabled *bool, started *bool, paused *bool, resumed *bool, completed *bool, canceled *bool, failed *bool, firstLayer *bool, thirdLayer *bool) (printerSettingsRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.records[printerID] + if !ok { + record = newDefaultPrinterSettingsRecord(printerID, "readonly") + } + if enabled != nil { + record.PrintNotificationsEnabled = *enabled + } + if started != nil { + record.NotifyPrintStarted = *started + } + if paused != nil { + record.NotifyPrintPaused = *paused + } + if resumed != nil { + record.NotifyPrintResumed = *resumed + } + if completed != nil { + record.NotifyPrintCompleted = *completed + } + if canceled != nil { + record.NotifyPrintCanceled = *canceled + } + if failed != nil { + record.NotifyPrintFailed = *failed + } + if firstLayer != nil { + record.NotifyFirstLayer = *firstLayer + } + if thirdLayer != nil { + record.NotifyThirdLayer = *thirdLayer + } + s.records[printerID] = record + if err := s.saveLocked(); err != nil { + delete(s.records, printerID) + return printerSettingsRecord{}, err + } + return record, nil +} + +func (s *printerSettingsStore) updateProfile(printerID string, displayName *string) (printerSettingsRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.records[printerID] + if !ok { + record = newDefaultPrinterSettingsRecord(printerID, "readonly") + } + if displayName != nil { + trimmed := strings.TrimSpace(*displayName) + if record.DisplayName != trimmed { + record.DisplayName = trimmed + record.DisplayNameUpdatedAt = time.Now().UTC() + } + } + s.records[printerID] = record + if err := s.saveLocked(); err != nil { + delete(s.records, printerID) + return printerSettingsRecord{}, err + } + return record, nil +} + +func (s *printerSettingsStore) markSynced(printerID string) error { + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.records[printerID] + if !ok { + return nil + } + record.LastSyncedAt = time.Now().UTC() + s.records[printerID] = record + return s.saveLocked() +} + +func (s *printerSettingsStore) updateInstall(printerID string, install printerInstallRecord) (printerSettingsRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.records[printerID] + if !ok { + record = newDefaultPrinterSettingsRecord(printerID, "readonly") + } + install.PrinterID = printerID + install.UpdatedAt = time.Now().UTC() + record.Install = &install + record.InstallHistory = append([]printerInstallRecord{install}, record.InstallHistory...) + if len(record.InstallHistory) > maxInstallHistoryEntries { + record.InstallHistory = record.InstallHistory[:maxInstallHistoryEntries] + } + s.records[printerID] = record + if err := s.saveLocked(); err != nil { + delete(s.records, printerID) + return printerSettingsRecord{}, err + } + return record, nil +} + +func (s *printerSettingsStore) updatePrintObservation(printerID string, observed *protocol.PrintStatus, notifySource string, notified bool, notifyError string) (printerSettingsRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.records[printerID] + if !ok { + record = printerSettingsRecord{ + PrinterID: printerID, + ControlMode: "readonly", + UIAutoDetect: true, + } + } + now := time.Now().UTC() + changed := false + if observed != nil { + state := strings.TrimSpace(observed.State) + file := strings.TrimSpace(observed.Filename) + if record.LastObservedPrintState != state || record.LastObservedPrintFile != file || record.LastObservedAt.IsZero() { + changed = true + } + record.LastObservedPrintState = state + record.LastObservedPrintFile = file + record.LastObservedAt = now + } + if notified { + if observed != nil { + state := strings.TrimSpace(observed.State) + file := strings.TrimSpace(observed.Filename) + if record.LastNotifiedPrintState != state || record.LastNotifiedPrintFile != file || record.LastNotifiedAt.IsZero() { + changed = true + } + record.LastNotifiedPrintState = state + record.LastNotifiedPrintFile = file + } + record.LastNotifiedAt = now + if record.LastNotificationSource != strings.TrimSpace(notifySource) || record.LastNotificationError != "" { + changed = true + } + record.LastNotificationSource = strings.TrimSpace(notifySource) + record.LastNotificationError = "" + } else if strings.TrimSpace(notifyError) != "" { + if record.LastNotificationError != strings.TrimSpace(notifyError) || record.LastNotificationSource != strings.TrimSpace(notifySource) || record.LastNotifiedAt.IsZero() { + changed = true + } + record.LastNotifiedAt = now + record.LastNotificationSource = strings.TrimSpace(notifySource) + record.LastNotificationError = strings.TrimSpace(notifyError) + } + if !changed { + return record, nil + } + s.records[printerID] = record + if err := s.saveLocked(); err != nil { + delete(s.records, printerID) + return printerSettingsRecord{}, err + } + return record, nil +} + +func (s *printerSettingsStore) updatePrintLayerObservation(printerID string, observed *protocol.PrintStatus, notifySource string, notified bool, notifyError string) (printerSettingsRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.records[printerID] + if !ok { + record = printerSettingsRecord{ + PrinterID: printerID, + ControlMode: "readonly", + UIAutoDetect: true, + } + } + now := time.Now().UTC() + changed := false + if observed != nil { + layer := observed.CurrentLayer + if record.LastObservedPrintLayer != layer || record.LastObservedAt.IsZero() { + changed = true + } + record.LastObservedPrintLayer = layer + record.LastObservedAt = now + } + if notified { + if observed != nil { + layer := observed.CurrentLayer + if record.LastLayerNotifiedPrintLayer != layer || record.LastLayerNotifiedAt.IsZero() { + changed = true + } + record.LastLayerNotifiedPrintLayer = layer + } + record.LastLayerNotifiedAt = now + if record.LastLayerNotificationSource != strings.TrimSpace(notifySource) || record.LastLayerNotificationError != "" { + changed = true + } + record.LastLayerNotificationSource = strings.TrimSpace(notifySource) + record.LastLayerNotificationError = "" + } else if strings.TrimSpace(notifyError) != "" { + if record.LastLayerNotificationError != strings.TrimSpace(notifyError) || record.LastLayerNotificationSource != strings.TrimSpace(notifySource) || record.LastLayerNotifiedAt.IsZero() { + changed = true + } + record.LastLayerNotifiedAt = now + record.LastLayerNotificationSource = strings.TrimSpace(notifySource) + record.LastLayerNotificationError = strings.TrimSpace(notifyError) + } + if !changed { + return record, nil + } + s.records[printerID] = record + if err := s.saveLocked(); err != nil { + delete(s.records, printerID) + return printerSettingsRecord{}, err + } + return record, nil +} + +func normalizeControlMode(mode string) string { + switch strings.ToLower(strings.TrimSpace(mode)) { + case "", "readonly": + return "readonly" + case "full": + return "full" + default: + return "" + } +} diff --git a/cmd/server/printer_settings_test.go b/cmd/server/printer_settings_test.go new file mode 100644 index 0000000..8191606 --- /dev/null +++ b/cmd/server/printer_settings_test.go @@ -0,0 +1,219 @@ +package main + +import ( + "path/filepath" + "strings" + "testing" + + "github.com/klipperanywhere/klipperanywhere/internal/protocol" +) + +func TestPrinterSettingsStoreSeedAndUpdate(t *testing.T) { + store, err := newPrinterSettingsStore(filepath.Join(t.TempDir(), "printer-settings.json")) + if err != nil { + t.Fatal(err) + } + + health := &protocol.Health{ + UIURL: "http://192.168.1.60", + UIAutoDetect: true, + ControlMode: "readonly", + } + record, created, err := store.ensureFromHealth("real-printer", health, "full") + if err != nil { + t.Fatal(err) + } + if !created { + t.Fatal("expected first seed to create a record") + } + if record.ControlMode != "full" || record.UIURL != "http://192.168.1.60" || !record.UIAutoDetect { + t.Fatalf("unexpected seed record: %+v", record) + } + + updated, err := store.update("real-printer", ptrString("Living room printer"), ptrString("full"), ptrString("http://printer-ui.local"), ptrBool(false), ptrString("nozzle"), "readonly") + if err != nil { + t.Fatal(err) + } + if updated.DisplayName != "Living room printer" || updated.ControlMode != "full" || updated.UIURL != "http://printer-ui.local" || updated.UIAutoDetect || updated.NotificationSnapshotCamera != "nozzle" { + t.Fatalf("unexpected updated record: %+v", updated) + } + + snapshot, ok := store.snapshot("real-printer") + if !ok { + t.Fatal("expected snapshot to exist") + } + if snapshot.DisplayName != "Living room printer" || snapshot.ControlMode != "full" || snapshot.UIURL != "http://printer-ui.local" || snapshot.UIAutoDetect || snapshot.NotificationSnapshotCamera != "nozzle" { + t.Fatalf("unexpected snapshot: %+v", snapshot) + } +} + +func TestPrinterSettingsUpdateDisplayNameOnly(t *testing.T) { + store, err := newPrinterSettingsStore(filepath.Join(t.TempDir(), "printer-settings.json")) + if err != nil { + t.Fatal(err) + } + updated, err := store.update("real-printer", ptrString("Workshop"), nil, nil, nil, nil, "readonly") + if err != nil { + t.Fatal(err) + } + if updated.DisplayName != "Workshop" { + t.Fatalf("unexpected display name: %+v", updated) + } + if updated.ControlMode != "readonly" { + t.Fatalf("unexpected control mode: %+v", updated) + } +} + +func TestPrinterSettingsUpdateInstallDetails(t *testing.T) { + store, err := newPrinterSettingsStore(filepath.Join(t.TempDir(), "printer-settings.json")) + if err != nil { + t.Fatal(err) + } + updated, err := store.updateInstall("real-printer", printerInstallRecord{ + Host: "192.168.1.60", + Port: 22, + Username: "root", + HostType: "rinkhals", + ServerURL: "http://192.168.1.35:8080", + MoonrakerURL: "http://127.0.0.1:7125", + UIURL: "http://192.168.1.60", + UIAutoDetect: true, + RequestedBy: "admin", + RemoteHost: "F005-02B0", + ReleaseURL: "https://example.com/releases/latest/download", + BinarySource: "release", + ConfigPath: "/tmp/agent.json", + BinaryPath: "/tmp/klipperanywhere-agent", + Message: "installed", + PostInstallConnected: true, + PostInstallMessage: "confirmed", + RollbackPerformed: false, + RollbackMessage: "", + Status: "installed", + }) + if err != nil { + t.Fatal(err) + } + if updated.Install == nil { + t.Fatal("expected install record") + } + if updated.Install.Host != "192.168.1.60" || updated.Install.Username != "root" || updated.Install.HostType != "rinkhals" || updated.Install.Status != "installed" { + t.Fatalf("unexpected install record: %+v", updated.Install) + } + if updated.Install.PrinterID != "real-printer" { + t.Fatalf("printer id = %q, want real-printer", updated.Install.PrinterID) + } + if len(updated.InstallHistory) != 1 { + t.Fatalf("expected 1 history entry, got %d", len(updated.InstallHistory)) + } + if updated.InstallHistory[0].PrinterID != "real-printer" || updated.InstallHistory[0].Status != "installed" { + t.Fatalf("unexpected history entry: %+v", updated.InstallHistory[0]) + } + snapshot, ok := store.snapshot("real-printer") + if !ok || snapshot.Install == nil { + t.Fatal("expected stored install snapshot") + } + if snapshot.Install.RequestedBy != "admin" || !snapshot.Install.PostInstallConnected { + t.Fatalf("unexpected snapshot install record: %+v", snapshot.Install) + } +} + +func TestPrinterSettingsUpdateNotifications(t *testing.T) { + store, err := newPrinterSettingsStore(filepath.Join(t.TempDir(), "printer-settings.json")) + if err != nil { + t.Fatal(err) + } + updated, err := store.updateNotifications("real-printer", ptrBool(true), ptrBool(true), ptrBool(false), ptrBool(true), ptrBool(true), ptrBool(false), ptrBool(true), ptrBool(true), ptrBool(false)) + if err != nil { + t.Fatal(err) + } + if !updated.PrintNotificationsEnabled || !updated.NotifyPrintStarted || updated.NotifyPrintPaused || !updated.NotifyPrintResumed || !updated.NotifyPrintCompleted || updated.NotifyPrintCanceled || !updated.NotifyPrintFailed || !updated.NotifyFirstLayer || updated.NotifyThirdLayer { + t.Fatalf("unexpected notification record: %+v", updated) + } + updated, err = store.updatePrintObservation("real-printer", &protocol.PrintStatus{State: "printing", Filename: "benchy.gcode"}, "telegram", true, "") + if err != nil { + t.Fatal(err) + } + if updated.LastObservedPrintState != "printing" || updated.LastNotifiedPrintState != "printing" { + t.Fatalf("unexpected observation record: %+v", updated) + } +} + +func TestPrinterSettingsUpdatePrintLayerObservation(t *testing.T) { + store, err := newPrinterSettingsStore(filepath.Join(t.TempDir(), "printer-settings.json")) + if err != nil { + t.Fatal(err) + } + updated, err := store.updatePrintLayerObservation("real-printer", &protocol.PrintStatus{State: "printing", Filename: "benchy.gcode", CurrentLayer: 1}, "telegram", true, "") + if err != nil { + t.Fatal(err) + } + if updated.LastObservedPrintLayer != 1 || updated.LastLayerNotifiedPrintLayer != 1 { + t.Fatalf("unexpected layer observation record: %+v", updated) + } +} + +func TestPrinterSettingsInstallHistoryAppends(t *testing.T) { + store, err := newPrinterSettingsStore(filepath.Join(t.TempDir(), "printer-settings.json")) + if err != nil { + t.Fatal(err) + } + if _, err := store.updateInstall("real-printer", printerInstallRecord{Status: "failed", Error: "first"}); err != nil { + t.Fatal(err) + } + if _, err := store.updateInstall("real-printer", printerInstallRecord{Status: "installed", Message: "second"}); err != nil { + t.Fatal(err) + } + snapshot, ok := store.snapshot("real-printer") + if !ok { + t.Fatal("expected snapshot") + } + if len(snapshot.InstallHistory) != 2 { + t.Fatalf("expected 2 history entries, got %d", len(snapshot.InstallHistory)) + } + if snapshot.InstallHistory[0].Status != "installed" || snapshot.InstallHistory[1].Status != "failed" { + t.Fatalf("unexpected history order: %+v", snapshot.InstallHistory) + } +} + +func TestNormalizeControlMode(t *testing.T) { + if got := normalizeControlMode("readonly"); got != "readonly" { + t.Fatalf("normalizeControlMode(readonly) = %q", got) + } + if got := normalizeControlMode("full"); got != "full" { + t.Fatalf("normalizeControlMode(full) = %q", got) + } + if got := normalizeControlMode("invalid"); got != "" { + t.Fatalf("normalizeControlMode(invalid) = %q", got) + } +} + +func TestDescribePrinterSettingsChange(t *testing.T) { + before := printerSettingsRecord{ + DisplayName: "Workshop", + ControlMode: "readonly", + UIURL: "http://192.168.1.60", + UIAutoDetect: true, + NotificationSnapshotCamera: "wide", + } + after := printerSettingsRecord{ + DisplayName: "Living room", + ControlMode: "full", + UIURL: "http://printer.local", + UIAutoDetect: false, + NotificationSnapshotCamera: "nozzle", + } + got := describePrinterSettingsChange(before, after) + if got == "" { + t.Fatal("expected non-empty description") + } + for _, want := range []string{"display_name", "control_mode", "ui_url", "ui_auto_detect", "notification_snapshot_camera"} { + if !strings.Contains(got, want) { + t.Fatalf("description %q missing %q", got, want) + } + } +} + +func ptrString(v string) *string { return &v } + +func ptrBool(v bool) *bool { return &v } diff --git a/cmd/server/ssh_install.go b/cmd/server/ssh_install.go new file mode 100644 index 0000000..b1d5b77 --- /dev/null +++ b/cmd/server/ssh_install.go @@ -0,0 +1,1160 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strings" + "time" + + "golang.org/x/crypto/ssh" +) + +const defaultReleaseBaseURL = "https://github.com/klipperanywhere/klipperanywhere/releases/latest/download" +const rinkhalsAppRoot = "/useremain/home/rinkhals/apps/60-klipperanywhere-agent" + +const ( + installHostTypeStandard = "standard" + installHostTypeRinkhals = "rinkhals" +) + +type sshInstallRequest struct { + Host string `json:"host"` + Port int `json:"port"` + Username string `json:"username"` + Password string `json:"password"` + HostType string `json:"host_type"` + ServerURL string `json:"server_url"` + PrinterID string `json:"printer_id"` + MoonrakerURL string `json:"moonraker_url"` + UIURL string `json:"ui_url"` + UIAutoDetect *bool `json:"ui_auto_detect"` +} + +type sshInstallResponse struct { + PrinterID string `json:"printer_id"` + Host string `json:"host"` + Port int `json:"port"` + RemoteHost string `json:"remote_host"` + HostType string `json:"host_type"` + Message string `json:"message"` + ReleaseURL string `json:"release_url"` + ServerURL string `json:"server_url"` + BinarySource string `json:"binary_source"` + ConfigPath string `json:"config_path"` + BinaryPath string `json:"binary_path"` + PostInstallConnected bool `json:"post_install_connected"` + PostInstallMessage string `json:"post_install_message"` + RollbackPerformed bool `json:"rollback_performed"` + RollbackMessage string `json:"rollback_message"` +} + +func (s *server) handleInstallPage(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/install" { + http.NotFound(w, r) + return + } + page, err := os.ReadFile("web/static/install.html") + if err != nil { + http.Error(w, "install page unavailable", http.StatusInternalServerError) + return + } + sess, ok := s.currentSession(r) + if !ok { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + page = []byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken)) + _, _ = w.Write(page) +} + +func (s *server) handleInstallSSHAPI(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.Header().Set("Allow", "POST") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + sess, ok := s.currentSession(r) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) + return + } + if sess.Role != "admin" { + http.Error(w, "admin access required", http.StatusForbidden) + return + } + if !s.verifyCSRF(w, r, sess) { + return + } + var req sshInstallRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + job, err := s.newInstallJob(req) + if err != nil { + http.Error(w, "failed to create install job", http.StatusInternalServerError) + return + } + job.addStep("queued", "Queued installer job.") + go s.runInstallSSHJob(context.Background(), requestOrigin(r), sess.Username, req, job) + writeJSON(w, http.StatusAccepted, map[string]any{ + "ok": true, + "job_id": job.ID, + "status": job.snapshot().Status, + "message": job.snapshot().Message, + "printer_id": job.PrinterID, + }) +} + +func (s *server) handleInstallSSHJobAPI(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.Header().Set("Allow", "GET") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + jobID := strings.TrimPrefix(r.URL.Path, "/api/install/ssh/jobs/") + if jobID == "" || jobID == r.URL.Path { + http.NotFound(w, r) + return + } + job, ok := s.getInstallJob(jobID) + if !ok { + http.NotFound(w, r) + return + } + writeJSON(w, http.StatusOK, job.snapshot()) +} + +func (s *server) runInstallSSHJob(ctx context.Context, origin string, actor string, req sshInstallRequest, job *installJob) { + job.markRunning("starting", "Starting installer job.") + resp, err := s.installPrinterOverSSH(ctx, origin, actor, req, func(stage, message string) { + job.addStep(stage, message) + }) + if err != nil { + job.finish("failed", "failed", err.Error(), nil, err) + s.logAudit(auditEvent{ + Actor: actor, + Action: actionLabel("printer_install_ssh"), + PrinterID: job.PrinterID, + Detail: fmt.Sprintf("failed to install printer agent on %s:%d (%s)", job.Host, job.Port, err.Error()), + }) + return + } + job.finish("succeeded", "complete", "Installer completed successfully.", &resp, nil) + s.logAudit(auditEvent{ + Actor: actor, + Action: actionLabel("printer_install_ssh"), + PrinterID: resp.PrinterID, + Detail: fmt.Sprintf("installed printer agent on %s:%d (%s)", resp.Host, resp.Port, resp.PostInstallMessage), + }) +} + +func (s *server) installPrinterOverSSH(ctx context.Context, origin string, actor string, req sshInstallRequest, progress func(stage, message string)) (resp sshInstallResponse, err error) { + host := strings.TrimSpace(req.Host) + if host == "" { + return sshInstallResponse{}, errors.New("host is required") + } + username := strings.TrimSpace(req.Username) + if username == "" { + return sshInstallResponse{}, errors.New("username is required") + } + password := req.Password + if password == "" { + return sshInstallResponse{}, errors.New("password is required") + } + port := req.Port + if port <= 0 { + port = 22 + } + hostType := normalizeInstallHostType(req.HostType) + if progress != nil { + progress("ssh", "Connecting to printer host over SSH.") + } + + client, err := dialSSH(host, port, username, password) + if err != nil { + return sshInstallResponse{}, err + } + defer client.Close() + + remoteHostOut, err := sshRunRetry(client, 3, 300*time.Millisecond, func() (string, error) { + return sshRun(client, "hostname") + }) + if err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to read remote hostname: %w", err) + } + remoteHost := strings.TrimSpace(remoteHostOut) + if progress != nil { + progress("ssh", fmt.Sprintf("Connected to %s. Detecting host architecture.", remoteHost)) + } + remoteArchOut, err := sshRunRetry(client, 3, 300*time.Millisecond, func() (string, error) { + return sshRun(client, `sh -lc 'uname -m 2>/dev/null || arch 2>/dev/null || echo unknown'`) + }) + if err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to detect remote architecture: %w", err) + } + remoteArch := strings.TrimSpace(remoteArchOut) + printerID := sanitizePrinterID(req.PrinterID) + if printerID == "" { + printerID = sanitizePrinterID(remoteHost) + } + if printerID == "" { + printerID = sanitizePrinterID(host) + } + if printerID == "" { + return sshInstallResponse{}, errors.New("printer id could not be determined") + } + serverURL, err := resolveInstallServerURL(origin, req.ServerURL) + if err != nil { + return sshInstallResponse{}, err + } + if progress != nil { + progress("build", fmt.Sprintf("Preparing %s binary for %s.", remoteArch, printerID)) + } + releaseURL := defaultReleaseBaseURL + installRecord := printerInstallRecord{ + Host: host, + Port: port, + Username: username, + HostType: hostType, + ServerURL: serverURL, + PrinterID: printerID, + MoonrakerURL: strings.TrimSpace(req.MoonrakerURL), + UIURL: strings.TrimSpace(req.UIURL), + UIAutoDetect: true, + RequestedBy: actor, + RemoteHost: remoteHost, + ReleaseURL: defaultReleaseBaseURL, + Status: "pending", + } + if req.UIAutoDetect != nil { + installRecord.UIAutoDetect = *req.UIAutoDetect + } + defer func() { + if printerID == "" { + return + } + if err != nil { + installRecord.Status = "failed" + installRecord.Error = err.Error() + } else { + installRecord.Status = "installed" + installRecord.Error = "" + installRecord.PostInstallConnected = resp.PostInstallConnected + installRecord.PostInstallMessage = resp.PostInstallMessage + installRecord.RollbackPerformed = resp.RollbackPerformed + installRecord.RollbackMessage = resp.RollbackMessage + if resp.ReleaseURL != "" { + installRecord.ReleaseURL = resp.ReleaseURL + } + if resp.BinarySource != "" { + installRecord.BinarySource = resp.BinarySource + } + if resp.ConfigPath != "" { + installRecord.ConfigPath = resp.ConfigPath + } + if resp.BinaryPath != "" { + installRecord.BinaryPath = resp.BinaryPath + } + if resp.Message != "" { + installRecord.Message = resp.Message + } + } + if _, saveErr := s.printerSettings.updateInstall(printerID, installRecord); saveErr != nil { + fmt.Printf("failed to persist install details printer_id=%s: %v\n", printerID, saveErr) + } + }() + + if hostType == installHostTypeRinkhals { + resp, err = s.installPrinterAsRinkhalsApp(ctx, client, printerID, serverURL, req, remoteArch, releaseURL, progress) + if err != nil { + return sshInstallResponse{}, err + } + resp.Host = host + resp.Port = port + resp.RemoteHost = remoteHost + resp.HostType = hostType + resp.ServerURL = requestAgentTunnelURL(serverURL) + return resp, nil + } + + remoteDirOut, err := sshRunRetry(client, 3, 300*time.Millisecond, func() (string, error) { + return sshRun(client, `sh -lc ' +for base in /tmp /var/tmp /data/local/tmp; do + tmpdir="$base/klipperanywhere-install-$$" + if mkdir -p "$tmpdir" 2>/dev/null; then + printf "%s\n" "$tmpdir" + exit 0 + fi +done +exit 1 +'`) + }) + if err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to create remote install directory: %w", err) + } + remoteDir := strings.TrimSpace(remoteDirOut) + if remoteDir == "" { + return sshInstallResponse{}, errors.New("remote install directory was empty") + } + if progress != nil { + progress("prepare", fmt.Sprintf("Using remote staging directory %s.", remoteDir)) + } + defer func() { + _, _ = sshRun(client, "rm -rf "+shellQuote(remoteDir)) + }() + spec, err := buildSpecForMachine(remoteArch) + if err != nil { + return sshInstallResponse{}, err + } + binary, binarySource, err := loadAgentBinary(ctx, releaseURL, spec) + if err != nil { + return sshInstallResponse{}, err + } + if progress != nil { + progress("download", describeLoadedAgentBinary(binarySource, releaseURL)) + } + config := buildSSHInstallConfig(serverURL, printerID, s.agentToken, req) + configPath := remoteDir + "/agent.json" + binaryPath := remoteDir + "/klipperanywhere-agent" + scriptDir := remoteDir + "/scripts" + installPath := scriptDir + "/install-agent.sh" + servicePath := remoteDir + "/packaging/klipperanywhere-agent.service" + initdPath := remoteDir + "/packaging/klipperanywhere-agent.initd" + + if _, err := sshRun(client, "mkdir -p "+shellQuote(scriptDir)+" "+shellQuote(remoteDir+"/packaging")); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to prepare remote files: %w", err) + } + if progress != nil { + progress("upload", "Uploading agent binary and installer files.") + } + if err := sshWriteFile(client, binaryPath, binary); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to upload agent binary: %w", err) + } + if progress != nil { + progress("upload", "Uploaded agent binary.") + } + if err := sshWriteFile(client, installPath, mustReadFile("scripts/install-agent.sh")); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to upload installer script: %w", err) + } + if progress != nil { + progress("upload", "Uploaded installer script.") + } + if err := sshWriteFile(client, servicePath, mustReadFile("packaging/klipperanywhere-agent.service")); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to upload service file: %w", err) + } + if progress != nil { + progress("upload", "Uploaded service file.") + } + if err := sshWriteFile(client, initdPath, mustReadFile("packaging/klipperanywhere-agent.initd")); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to upload init script: %w", err) + } + if progress != nil { + progress("upload", "Uploaded init script.") + } + if err := sshWriteFile(client, configPath, config); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to upload agent config: %w", err) + } + if progress != nil { + progress("upload", "Uploaded agent config.") + } + if _, err := sshRun(client, "chmod 0755 "+shellQuote(binaryPath)+" "+shellQuote(installPath)); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to prepare remote scripts: %w", err) + } + if _, err := sshRun(client, "chmod 0644 "+shellQuote(servicePath)+" "+shellQuote(initdPath)); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to prepare remote packaging files: %w", err) + } + if _, err := sshRun(client, "chmod 0600 "+shellQuote(configPath)); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to secure remote config: %w", err) + } + if progress != nil { + progress("install", "Prepared remote installer files.") + } + hadExistingInstall := remoteExistingInstall(client) + competingInstallMessage, err := disableCompetingAgentInstall(client, installHostTypeStandard, rinkhalsAppRoot) + if err != nil { + return sshInstallResponse{}, err + } + if progress != nil && competingInstallMessage != "" { + progress("install", competingInstallMessage) + } + if progress != nil { + progress("install", "Running installer on remote host.") + } + command := strings.Join([]string{"sh", shellQuote(installPath), shellQuote(binaryPath), shellQuote(configPath)}, " ") + output, err := sshRun(client, command) + if err != nil { + if strings.TrimSpace(output) != "" { + return sshInstallResponse{}, fmt.Errorf("%w: %s", err, strings.TrimSpace(output)) + } + return sshInstallResponse{}, err + } + reconnectTimeout := 20 * time.Second + if hostType == installHostTypeRinkhals { + reconnectTimeout = 2 * time.Minute + } + connected, postInstallMessage, err := s.waitForPrinterConnection(ctx, printerID, reconnectTimeout) + if err != nil { + return sshInstallResponse{}, err + } + if progress != nil { + if connected { + progress("callback", "Agent connected back to the server.") + } else { + progress("callback", "Waiting for agent callback.") + } + } + postInstallMessage = appendPostInstallNote(postInstallMessage, competingInstallMessage) + rollbackPerformed := false + rollbackMessage := "" + if !connected && hadExistingInstall { + if rollbackOutput, rollbackErr := rollbackPrinterInstall(client); rollbackErr != nil { + return sshInstallResponse{}, fmt.Errorf("installed agent but rollback failed after reconnect timeout: %w", rollbackErr) + } else { + rollbackPerformed = true + rollbackMessage = strings.TrimSpace(rollbackOutput) + connected, postInstallMessage, err = s.waitForPrinterConnection(ctx, printerID, reconnectTimeout) + if err != nil { + return sshInstallResponse{}, err + } + if rollbackMessage == "" { + rollbackMessage = "restored previous agent installation after reconnect timeout" + } + if connected { + postInstallMessage = "Previous agent restored after the replacement failed to reconnect." + } else { + postInstallMessage = "Replacement agent did not reconnect; previous installation was restored." + } + } + } + + resp = sshInstallResponse{ + PrinterID: printerID, + Host: host, + Port: port, + RemoteHost: remoteHost, + HostType: hostType, + Message: strings.TrimSpace(output), + ReleaseURL: releaseURL, + ServerURL: requestAgentTunnelURL(serverURL), + BinarySource: binarySource, + ConfigPath: configPath, + BinaryPath: binaryPath, + PostInstallConnected: connected, + PostInstallMessage: postInstallMessage, + RollbackPerformed: rollbackPerformed, + RollbackMessage: rollbackMessage, + } + return resp, nil +} + +func normalizeInstallHostType(value string) string { + switch strings.ToLower(strings.TrimSpace(value)) { + case "", installHostTypeStandard: + return installHostTypeStandard + case installHostTypeRinkhals: + return installHostTypeRinkhals + default: + return installHostTypeStandard + } +} + +func buildSSHInstallConfig(serverURL string, printerID string, agentToken string, req sshInstallRequest) []byte { + return buildSSHInstallConfigWithStateFile(serverURL, printerID, agentToken, req, "") +} + +func buildSSHInstallConfigWithStateFile(serverURL string, printerID string, agentToken string, req sshInstallRequest, stateFile string) []byte { + uiAutoDetect := true + if req.UIAutoDetect != nil { + uiAutoDetect = *req.UIAutoDetect + } + cfg := map[string]any{ + "server_url": requestAgentTunnelURL(serverURL), + "printer_id": printerID, + "token": agentToken, + "moonraker_url": strings.TrimSpace(req.MoonrakerURL), + "ui_auto_detect": uiAutoDetect, + } + if cfg["moonraker_url"] == "" { + cfg["moonraker_url"] = "http://127.0.0.1:7125" + } + if uiURL := strings.TrimSpace(req.UIURL); uiURL != "" { + cfg["ui_url"] = uiURL + } + if stateFile = strings.TrimSpace(stateFile); stateFile != "" { + cfg["state_file"] = stateFile + } + encoded, err := json.MarshalIndent(cfg, "", " ") + if err != nil { + return []byte("{}\n") + } + return append(encoded, '\n') +} + +func (s *server) installPrinterAsRinkhalsApp(ctx context.Context, client *ssh.Client, printerID, serverURL string, req sshInstallRequest, remoteArch string, releaseURL string, progress func(stage, message string)) (sshInstallResponse, error) { + appRoot := rinkhalsAppRoot + appLogPath := filepath.Join(appRoot, "klipperanywhere-agent.log") + stageRoot := filepath.Join(appRoot, "staging") + hadExistingInstall := remoteExistingRinkhalsInstall(client, appRoot) + if _, err := sshRun(client, "mkdir -p "+shellQuote(appRoot)+" "+shellQuote(filepath.Join(appRoot, "rollback"))); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals app directory: %w", err) + } + if progress != nil { + progress("prepare", fmt.Sprintf("Preparing Rinkhals app directory at %s.", appRoot)) + } + + spec, err := buildSpecForMachine(remoteArch) + if err != nil { + return sshInstallResponse{}, err + } + binary, binarySource, err := loadAgentBinary(ctx, releaseURL, spec) + if err != nil { + return sshInstallResponse{}, err + } + if progress != nil { + progress("download", describeLoadedAgentBinary(binarySource, releaseURL)) + } + + configPath := filepath.Join(appRoot, "agent.json") + config := buildSSHInstallConfigWithStateFile(serverURL, printerID, s.agentToken, req, filepath.Join(appRoot, "agent-state.json")) + binaryPath := filepath.Join(appRoot, "klipperanywhere-agent") + appJSONPath := filepath.Join(appRoot, "app.json") + appSHPath := filepath.Join(appRoot, "app.sh") + enabledPath := filepath.Join(appRoot, ".enabled") + rollbackDir := filepath.Join(appRoot, "rollback") + stageConfigPath := filepath.Join(stageRoot, "agent.json") + stageBinaryPath := filepath.Join(stageRoot, "klipperanywhere-agent") + stageAppJSONPath := filepath.Join(stageRoot, "app.json") + stageAppSHPath := filepath.Join(stageRoot, "app.sh") + stageEnabledPath := filepath.Join(stageRoot, ".enabled") + + if hadExistingInstall { + if _, err := sshRun(client, "sh "+shellQuote(appSHPath)+" stop >/dev/null 2>&1 || true"); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to stop existing rinkhals app before reinstall: %w", err) + } + if progress != nil { + progress("install", "Stopped existing Rinkhals app before update.") + } + } + + if _, err := sshRun(client, "rm -rf "+shellQuote(stageRoot)+" && mkdir -p "+shellQuote(stageRoot)); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals staging directory: %w", err) + } + if progress != nil { + progress("prepare", fmt.Sprintf("Using Rinkhals staging directory %s.", stageRoot)) + } + + if hadExistingInstall { + if _, err := sshRun(client, "mkdir -p "+shellQuote(rollbackDir)); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals rollback directory: %w", err) + } + if progress != nil { + progress("prepare", "Backed up existing Rinkhals app files.") + } + for _, entry := range []struct { + src string + dst string + }{ + {binaryPath, filepath.Join(rollbackDir, "klipperanywhere-agent.bak")}, + {configPath, filepath.Join(rollbackDir, "agent.json.bak")}, + {appJSONPath, filepath.Join(rollbackDir, "app.json.bak")}, + {appSHPath, filepath.Join(rollbackDir, "app.sh.bak")}, + {enabledPath, filepath.Join(rollbackDir, ".enabled.bak")}, + } { + if _, statErr := sshRun(client, "sh -lc 'if [ -f "+entry.src+" ]; then cp "+entry.src+" "+entry.dst+"; fi'"); statErr != nil { + return sshInstallResponse{}, fmt.Errorf("failed to back up %s: %w", entry.src, statErr) + } + } + } + + if progress != nil { + progress("upload", "Uploading Rinkhals app bundle.") + } + if err := sshWriteFile(client, stageBinaryPath, binary); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to upload agent binary: %w", err) + } + if progress != nil { + progress("upload", "Uploaded Rinkhals agent binary.") + } + if err := sshWriteFile(client, stageAppJSONPath, mustReadFile("packaging/rinkhals/klipperanywhere-agent/app.json")); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to upload rinkhals app manifest: %w", err) + } + if progress != nil { + progress("upload", "Uploaded Rinkhals app manifest.") + } + if err := sshWriteFile(client, stageAppSHPath, mustReadFile("packaging/rinkhals/klipperanywhere-agent/app.sh")); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to upload rinkhals app script: %w", err) + } + if progress != nil { + progress("upload", "Uploaded Rinkhals app launcher.") + } + if err := sshWriteFile(client, stageConfigPath, config); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to upload agent config: %w", err) + } + if progress != nil { + progress("upload", "Uploaded Rinkhals agent config.") + } + if _, err := sshRun(client, "chmod 0755 "+shellQuote(stageBinaryPath)+" "+shellQuote(stageAppSHPath)); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals scripts: %w", err) + } + if _, err := sshRun(client, "chmod 0644 "+shellQuote(stageAppJSONPath)+" "+shellQuote(stageConfigPath)); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals data files: %w", err) + } + if _, err := sshRun(client, "sh -lc 'touch "+stageEnabledPath+"'"); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to enable rinkhals app: %w", err) + } + if _, err := sshRun(client, "sh -lc 'cp -f "+shellQuote(stageBinaryPath)+" "+shellQuote(binaryPath)+" && cp -f "+shellQuote(stageAppJSONPath)+" "+shellQuote(appJSONPath)+" && cp -f "+shellQuote(stageAppSHPath)+" "+shellQuote(appSHPath)+" && cp -f "+shellQuote(stageConfigPath)+" "+shellQuote(configPath)+" && cp -f "+shellQuote(stageEnabledPath)+" "+shellQuote(enabledPath)+"'"); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to activate rinkhals app staging files: %w", err) + } + if progress != nil { + progress("install", "Activated Rinkhals app files.") + } + if _, err := sshRun(client, "chmod 0755 "+shellQuote(binaryPath)+" "+shellQuote(appSHPath)); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals scripts: %w", err) + } + if _, err := sshRun(client, "chmod 0644 "+shellQuote(appJSONPath)+" "+shellQuote(configPath)); err != nil { + return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals data files: %w", err) + } + output, err := sshRun(client, "sh "+shellQuote(appSHPath)+" start") + if err != nil { + if strings.TrimSpace(output) != "" { + return sshInstallResponse{}, fmt.Errorf("%w: %s", err, strings.TrimSpace(output)) + } + return sshInstallResponse{}, err + } + competingInstallMessage, err := disableCompetingAgentInstall(client, installHostTypeRinkhals, appRoot) + if err != nil { + return sshInstallResponse{}, err + } + if progress != nil && competingInstallMessage != "" { + progress("install", competingInstallMessage) + } + + connected, postInstallMessage, err := s.waitForPrinterConnection(ctx, printerID, 20*time.Second) + if err != nil { + return sshInstallResponse{}, err + } + if progress != nil { + if connected { + progress("callback", "Rinkhals app connected back to the server.") + } else { + progress("callback", "Waiting for Rinkhals app callback.") + } + } + postInstallMessage = appendPostInstallNote(postInstallMessage, competingInstallMessage) + rollbackPerformed := false + rollbackMessage := "" + if !connected && hadExistingInstall { + if rollbackOutput, rollbackErr := rollbackRinkhalsInstall(client, appRoot); rollbackErr != nil { + return sshInstallResponse{}, fmt.Errorf("installed rinkhals app but rollback failed after reconnect timeout: %w", rollbackErr) + } else { + rollbackPerformed = true + rollbackMessage = strings.TrimSpace(rollbackOutput) + connected, postInstallMessage, err = s.waitForPrinterConnection(ctx, printerID, 20*time.Second) + if err != nil { + return sshInstallResponse{}, err + } + if rollbackMessage == "" { + rollbackMessage = "restored previous rinkhals app installation after reconnect timeout" + } + if connected { + postInstallMessage = "Previous Rinkhals app restored after the replacement failed to reconnect." + } else { + postInstallMessage = "Replacement Rinkhals app did not reconnect; previous installation was restored." + if logTail, tailErr := sshRun(client, "sh -lc 'tail -n 80 "+shellQuote(appLogPath)+" 2>/dev/null || true'"); tailErr == nil && strings.TrimSpace(logTail) != "" { + postInstallMessage += "\n\nApp log:\n" + strings.TrimSpace(logTail) + } + } + } + } + if !connected && !hadExistingInstall { + if logTail, tailErr := sshRun(client, "sh -lc 'tail -n 80 "+shellQuote(appLogPath)+" 2>/dev/null || true'"); tailErr == nil && strings.TrimSpace(logTail) != "" { + postInstallMessage += "\n\nApp log:\n" + strings.TrimSpace(logTail) + } + } + + return sshInstallResponse{ + PrinterID: printerID, + HostType: installHostTypeRinkhals, + Message: strings.TrimSpace(output), + ReleaseURL: releaseURL, + ServerURL: requestAgentTunnelURL(serverURL), + BinarySource: binarySource, + ConfigPath: configPath, + BinaryPath: binaryPath, + PostInstallConnected: connected, + PostInstallMessage: postInstallMessage, + RollbackPerformed: rollbackPerformed, + RollbackMessage: rollbackMessage, + }, nil +} + +func resolveInstallServerURL(origin string, raw string) (string, error) { + serverURL := strings.TrimSpace(raw) + if serverURL == "" { + if originIsLoopback(origin) { + return "", errors.New("server_url is required when the server is opened on localhost; enter the printer-reachable server URL") + } + serverURL = origin + } + parsed, err := url.Parse(serverURL) + if err != nil { + return "", fmt.Errorf("invalid server_url: %w", err) + } + if parsed.Scheme != "http" && parsed.Scheme != "https" { + return "", errors.New("server_url must start with http:// or https://") + } + if parsed.Host == "" { + return "", errors.New("server_url must include a host") + } + if isLoopbackHost(parsed.Hostname()) { + return "", errors.New("server_url must be reachable from the printer host; use the LAN IP or hostname") + } + return strings.TrimRight(parsed.String(), "/"), nil +} + +func requestAgentTunnelURL(origin string) string { + origin = strings.TrimSpace(origin) + origin = strings.TrimSuffix(origin, "/") + if strings.HasPrefix(origin, "https://") { + return "wss://" + strings.TrimPrefix(origin, "https://") + "/agent/tunnel" + } + if strings.HasPrefix(origin, "http://") { + return "ws://" + strings.TrimPrefix(origin, "http://") + "/agent/tunnel" + } + return origin + "/agent/tunnel" +} + +type agentBuildSpec struct { + Asset string + GOARCH string + GOARM string + GOMIPS string +} + +func buildSpecForMachine(machine string) (agentBuildSpec, error) { + switch strings.ToLower(strings.TrimSpace(machine)) { + case "x86_64", "amd64": + return agentBuildSpec{Asset: "klipperanywhere-agent-linux-amd64", GOARCH: "amd64"}, nil + case "aarch64", "arm64": + return agentBuildSpec{Asset: "klipperanywhere-agent-linux-arm64", GOARCH: "arm64"}, nil + case "armv7l", "armv7", "armv7hf", "armv7hl": + return agentBuildSpec{Asset: "klipperanywhere-agent-linux-armv7", GOARCH: "arm", GOARM: "7"}, nil + case "mips64el", "mipsle", "mipsel", "mips": + return agentBuildSpec{Asset: "klipperanywhere-agent-linux-mipsle", GOARCH: "mipsle", GOMIPS: "softfloat"}, nil + default: + return agentBuildSpec{}, fmt.Errorf("unsupported remote architecture: %s", machine) + } +} + +func releaseAssetForMachine(machine string) (string, error) { + spec, err := buildSpecForMachine(machine) + if err != nil { + return "", err + } + return spec.Asset, nil +} + +func loadAgentBinary(ctx context.Context, releaseURL string, spec agentBuildSpec) ([]byte, string, error) { + if binary, err := buildAgentBinaryFromSource(ctx, spec); err == nil { + return binary, "source", nil + } + if binary, err := loadBundledAgentBinary(spec); err == nil { + return binary, "bundled", nil + } + binary, err := downloadReleaseAsset(ctx, releaseURL, spec.Asset) + if err != nil { + return nil, "", err + } + return binary, "release", nil +} + +func loadBundledAgentBinary(spec agentBuildSpec) ([]byte, error) { + if spec.GOARCH != runtime.GOARCH || spec.GOARM != "" || spec.GOMIPS != "" || runtime.GOOS != "linux" { + return nil, fmt.Errorf("bundled agent binary is not compatible with target architecture") + } + return os.ReadFile("/usr/local/bin/klipperanywhere-agent") +} + +func describeLoadedAgentBinary(source string, releaseURL string) string { + switch strings.TrimSpace(source) { + case "source": + return "Built agent binary from the server container source." + case "bundled": + return "Loaded bundled agent binary from the server container." + case "release": + return fmt.Sprintf("Downloaded release agent binary from %s.", strings.TrimSpace(releaseURL)) + default: + return fmt.Sprintf("Loaded %s agent binary.", strings.TrimSpace(source)) + } +} + +func buildAgentBinaryFromSource(ctx context.Context, spec agentBuildSpec) ([]byte, error) { + goPath, err := exec.LookPath("go") + if err != nil { + return nil, err + } + tmpDir, err := os.MkdirTemp("", "klipperanywhere-agent-build-*") + if err != nil { + return nil, err + } + defer os.RemoveAll(tmpDir) + outputPath := filepath.Join(tmpDir, "klipperanywhere-agent") + cmd := exec.CommandContext(ctx, goPath, "build", "-trimpath", "-ldflags", "-X main.agentVersion="+serverVersion, "-o", outputPath, "./cmd/agent") + cmd.Env = append(os.Environ(), + "CGO_ENABLED=0", + "GOOS=linux", + "GOARCH="+spec.GOARCH, + ) + if spec.GOARM != "" { + cmd.Env = append(cmd.Env, "GOARM="+spec.GOARM) + } + if spec.GOMIPS != "" { + cmd.Env = append(cmd.Env, "GOMIPS="+spec.GOMIPS) + } + out, err := cmd.CombinedOutput() + if err != nil { + if len(out) > 0 { + return nil, fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out))) + } + return nil, err + } + return os.ReadFile(outputPath) +} + +func downloadReleaseAsset(ctx context.Context, baseURL string, asset string) ([]byte, error) { + baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") + url := baseURL + "/" + asset + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + client := &http.Client{Timeout: 2 * time.Minute} + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode > 299 { + snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) + if len(snippet) > 0 { + return nil, fmt.Errorf("download failed: %s: %s", resp.Status, strings.TrimSpace(string(snippet))) + } + return nil, fmt.Errorf("download failed: %s", resp.Status) + } + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + return body, nil +} + +func remoteExistingInstall(client *ssh.Client) bool { + output, err := sshRun(client, `sh -lc 'if [ -f /usr/local/bin/klipperanywhere-agent ] || [ -f /etc/klipperanywhere/agent.json ]; then echo yes; fi'`) + return err == nil && strings.TrimSpace(output) != "" +} + +func remoteExistingRinkhalsInstall(client *ssh.Client, appRoot string) bool { + output, err := sshRun(client, `sh -lc 'if [ -f `+filepath.Join(appRoot, "klipperanywhere-agent")+` ] || [ -f `+filepath.Join(appRoot, "agent.json")+` ]; then echo yes; fi'`) + return err == nil && strings.TrimSpace(output) != "" +} + +func disableCompetingAgentInstall(client *ssh.Client, activeHostType string, appRoot string) (string, error) { + switch normalizeInstallHostType(activeHostType) { + case installHostTypeRinkhals: + return disableLegacyAgentInstall(client) + default: + return disableRinkhalsAgentInstall(client, appRoot) + } +} + +func disableLegacyAgentInstall(client *ssh.Client) (string, error) { + command := `sh -lc ' +set +e +changed=0 +if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then + systemctl stop klipperanywhere-agent >/dev/null 2>&1 && changed=1 + systemctl disable klipperanywhere-agent >/dev/null 2>&1 && changed=1 + rm -f /etc/systemd/system/klipperanywhere-agent.service + systemctl daemon-reload >/dev/null 2>&1 +fi +if command -v rc-service >/dev/null 2>&1; then + rc-service klipperanywhere-agent stop >/dev/null 2>&1 && changed=1 +fi +if command -v rc-update >/dev/null 2>&1; then + rc-update del klipperanywhere-agent default >/dev/null 2>&1 && changed=1 +fi +if [ -x /etc/init.d/klipperanywhere-agent ]; then + /etc/init.d/klipperanywhere-agent stop >/dev/null 2>&1 && changed=1 +fi +if command -v update-rc.d >/dev/null 2>&1; then + update-rc.d -f klipperanywhere-agent remove >/dev/null 2>&1 && changed=1 +fi +if command -v chkconfig >/dev/null 2>&1; then + chkconfig --del klipperanywhere-agent >/dev/null 2>&1 && changed=1 +fi +rm -f /etc/rcS.d/S99klipperanywhere-agent /etc/rc.d/S99klipperanywhere-agent 2>/dev/null +if [ "$changed" -eq 1 ]; then + echo "Disabled legacy klipperanywhere-agent service to prevent duplicate connections." +fi +exit 0 +'` + output, err := sshRun(client, command) + if err != nil { + return "", fmt.Errorf("failed to disable legacy agent service: %w", err) + } + return strings.TrimSpace(output), nil +} + +func disableRinkhalsAgentInstall(client *ssh.Client, appRoot string) (string, error) { + appSH := filepath.Join(appRoot, "app.sh") + enabledPath := filepath.Join(appRoot, ".enabled") + command := "sh -lc " + shellQuote(` +set +e +changed=0 +if [ -x `+shellQuote(appSH)+` ]; then + sh `+shellQuote(appSH)+` stop >/dev/null 2>&1 && changed=1 +fi +if [ -f `+shellQuote(enabledPath)+` ]; then + rm -f `+shellQuote(enabledPath)+` + changed=1 +fi +if [ "$changed" -eq 1 ]; then + echo "Disabled Rinkhals klipperanywhere-agent app to prevent duplicate connections." +fi +exit 0 +`) + output, err := sshRun(client, command) + if err != nil { + return "", fmt.Errorf("failed to disable rinkhals agent app: %w", err) + } + return strings.TrimSpace(output), nil +} + +func appendPostInstallNote(message string, note string) string { + message = strings.TrimSpace(message) + note = strings.TrimSpace(note) + if note == "" { + return message + } + if message == "" { + return note + } + return message + " " + note +} + +func rollbackPrinterInstall(client *ssh.Client) (string, error) { + command := `sh -lc ' +set -eu +ROLLBACK_DIR=/var/lib/klipperanywhere/rollback +if [ ! -d "$ROLLBACK_DIR" ]; then + echo "no rollback backup available" + exit 1 +fi +if [ -f "$ROLLBACK_DIR/klipperanywhere-agent.bak" ]; then + install -m 0755 "$ROLLBACK_DIR/klipperanywhere-agent.bak" /usr/local/bin/klipperanywhere-agent +fi +if [ -f "$ROLLBACK_DIR/agent.json.bak" ]; then + install -m 0600 "$ROLLBACK_DIR/agent.json.bak" /etc/klipperanywhere/agent.json +fi +if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then + systemctl restart klipperanywhere-agent + systemctl status klipperanywhere-agent --no-pager || true + exit 0 +fi +if command -v rc-service >/dev/null 2>&1; then + rc-service klipperanywhere-agent restart 2>/dev/null || rc-service klipperanywhere-agent start + rc-service klipperanywhere-agent status || true + exit 0 +fi +if [ -x /etc/init.d/klipperanywhere-agent ]; then + /etc/init.d/klipperanywhere-agent restart + /etc/init.d/klipperanywhere-agent status || true + exit 0 +fi +echo "restored previous agent files" +'` + return sshRun(client, command) +} + +func rollbackRinkhalsInstall(client *ssh.Client, appRoot string) (string, error) { + rollbackDir := filepath.Join(appRoot, "rollback") + if _, err := sshRun(client, "test -d "+shellQuote(rollbackDir)); err != nil { + return "", err + } + for _, entry := range []struct { + src string + dst string + }{ + {filepath.Join(rollbackDir, "klipperanywhere-agent.bak"), filepath.Join(appRoot, "klipperanywhere-agent")}, + {filepath.Join(rollbackDir, "agent.json.bak"), filepath.Join(appRoot, "agent.json")}, + {filepath.Join(rollbackDir, "app.json.bak"), filepath.Join(appRoot, "app.json")}, + {filepath.Join(rollbackDir, "app.sh.bak"), filepath.Join(appRoot, "app.sh")}, + {filepath.Join(rollbackDir, ".enabled.bak"), filepath.Join(appRoot, ".enabled")}, + } { + if _, err := sshRun(client, "sh -lc 'if [ -f "+shellQuote(entry.src)+" ]; then cp "+shellQuote(entry.src)+" "+shellQuote(entry.dst)+"; fi'"); err != nil { + return "", err + } + } + if _, err := sshRun(client, "chmod 0755 "+shellQuote(filepath.Join(appRoot, "klipperanywhere-agent"))+" "+shellQuote(filepath.Join(appRoot, "app.sh"))+" 2>/dev/null || true"); err != nil { + return "", err + } + if _, err := sshRun(client, "chmod 0644 "+shellQuote(filepath.Join(appRoot, "agent.json"))+" "+shellQuote(filepath.Join(appRoot, "app.json"))+" 2>/dev/null || true"); err != nil { + return "", err + } + return sshRun(client, "sh "+shellQuote(filepath.Join(appRoot, "app.sh"))+" start") +} + +func dialSSH(host string, port int, username string, password string) (*ssh.Client, error) { + addr := net.JoinHostPort(host, fmt.Sprintf("%d", port)) + conn, err := net.DialTimeout("tcp", addr, 15*time.Second) + if err != nil { + return nil, err + } + cfg := &ssh.ClientConfig{ + User: username, + Auth: []ssh.AuthMethod{ssh.Password(password)}, + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + Timeout: 15 * time.Second, + } + cc, chans, reqs, err := ssh.NewClientConn(conn, addr, cfg) + if err != nil { + _ = conn.Close() + return nil, err + } + return ssh.NewClient(cc, chans, reqs), nil +} + +func sshRun(client *ssh.Client, command string) (string, error) { + session, err := client.NewSession() + if err != nil { + return "", err + } + defer session.Close() + var out bytes.Buffer + session.Stdout = &out + session.Stderr = &out + err = session.Run(command) + return out.String(), err +} + +func sshRunRetry(client *ssh.Client, attempts int, delay time.Duration, run func() (string, error)) (string, error) { + if attempts < 1 { + attempts = 1 + } + var lastOut string + var lastErr error + for i := 0; i < attempts; i++ { + out, err := run() + lastOut = out + if err == nil && strings.TrimSpace(out) != "" { + return out, nil + } + lastErr = err + if i < attempts-1 { + time.Sleep(delay) + } + } + if lastErr != nil { + return lastOut, lastErr + } + return lastOut, errors.New("empty response") +} + +func sshWriteFile(client *ssh.Client, path string, contents []byte) error { + session, err := client.NewSession() + if err != nil { + return err + } + defer session.Close() + session.Stdin = bytes.NewReader(contents) + command := "sh -c 'cat > \"$1\"' sh " + shellQuote(path) + return session.Run(command) +} + +func sanitizePrinterID(value string) string { + value = strings.TrimSpace(value) + if value == "" { + return "" + } + cleaned := printerIDCleaner.ReplaceAllString(value, "-") + cleaned = strings.Trim(cleaned, "-") + return cleaned +} + +var printerIDCleaner = regexp.MustCompile(`[^A-Za-z0-9._-]+`) + +func shellQuote(value string) string { + if value == "" { + return "''" + } + return "'" + strings.ReplaceAll(value, "'", `'"'"'`) + "'" +} + +func mustReadFile(path string) []byte { + data, err := os.ReadFile(path) + if err != nil { + panic(err) + } + return data +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return value + } + } + return "" +} + +func originIsLoopback(origin string) bool { + origin = strings.ToLower(strings.TrimSpace(origin)) + return strings.Contains(origin, "://127.0.0.1") || strings.Contains(origin, "://localhost") || strings.Contains(origin, "://[::1]") +} + +func isLoopbackHost(host string) bool { + host = strings.ToLower(strings.TrimSpace(host)) + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +func (s *server) printerConnected(printerID string) bool { + s.tunnelsMu.RLock() + _, ok := s.tunnels[printerID] + s.tunnelsMu.RUnlock() + return ok +} + +func (s *server) waitForPrinterConnection(ctx context.Context, printerID string, timeout time.Duration) (bool, string, error) { + waitCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + for { + if s.printerConnected(printerID) { + return true, "Agent appeared in /api/printers.", nil + } + select { + case <-waitCtx.Done(): + return false, "Installed, but the agent has not appeared in /api/printers yet.", nil + case <-ticker.C: + } + } +} diff --git a/cmd/server/telegram_bot.go b/cmd/server/telegram_bot.go new file mode 100644 index 0000000..ddfedc9 --- /dev/null +++ b/cmd/server/telegram_bot.go @@ -0,0 +1,1776 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "net/url" + "path" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/klipperanywhere/klipperanywhere/internal/protocol" +) + +type telegramBot struct { + client *http.Client + settings *notificationSettingsStore + server *server + mu sync.Mutex + menuMu sync.Mutex + menuState string + selections map[string]telegramPrintSelection + cameraSelections map[string]telegramCameraSelection + temperatureSelections map[string]telegramTemperatureSelection +} + +type telegramUpdate struct { + UpdateID int64 `json:"update_id"` + Message *telegramMessage `json:"message,omitempty"` + CallbackQuery *telegramCallbackQuery `json:"callback_query,omitempty"` +} + +type telegramMessage struct { + MessageID int64 `json:"message_id"` + Chat telegramChat `json:"chat"` + Text string `json:"text,omitempty"` +} + +type telegramChat struct { + ID int64 `json:"id"` +} + +type telegramCallbackQuery struct { + ID string `json:"id"` + From telegramUser `json:"from"` + Data string `json:"data,omitempty"` + Message *telegramMessage `json:"message,omitempty"` +} + +type telegramUser struct { + ID int64 `json:"id"` +} + +type telegramPrintSelection struct { + PrinterID string + Filename string + Label string + CreatedAt time.Time +} + +type telegramCameraSelection struct { + PrinterID string + CameraName string + CreatedAt time.Time +} + +type telegramTemperatureSelection struct { + PrinterID string + Heater string + Target float64 + CreatedAt time.Time +} + +type telegramPrintableJob struct { + Filename string + Label string + ButtonLabel string +} + +type telegramCallbackAction struct { + Kind string + ID string +} + +func (b *telegramBot) run(ctx context.Context) { + if b == nil || b.client == nil || b.settings == nil || b.server == nil { + return + } + offset := int64(0) + backoff := 5 * time.Second + for { + select { + case <-ctx.Done(): + return + default: + } + + enabled, token, chatID := b.commandCredentials() + if !enabled || token == "" || chatID == "" { + if err := b.syncCommandMenu(ctx, token, false, false); err != nil { + log.Printf("telegram bot command menu update failed: %v", err) + } + select { + case <-time.After(10 * time.Second): + case <-ctx.Done(): + return + } + continue + } + if err := b.syncCommandMenu(ctx, token, true, true); err != nil { + log.Printf("telegram bot command menu update failed: %v", err) + } + + updates, err := b.fetchUpdates(ctx, token, offset) + if err != nil { + log.Printf("telegram bot polling failed: %v", err) + select { + case <-time.After(backoff): + case <-ctx.Done(): + return + } + if backoff < 30*time.Second { + backoff *= 2 + if backoff > 30*time.Second { + backoff = 30 * time.Second + } + } + continue + } + backoff = 5 * time.Second + for _, update := range updates { + if update.UpdateID >= offset { + offset = update.UpdateID + 1 + } + if update.CallbackQuery != nil { + if update.CallbackQuery.Message != nil && strconv.FormatInt(update.CallbackQuery.Message.Chat.ID, 10) != chatID { + continue + } + if err := b.handleCallbackQuery(ctx, token, chatID, update.CallbackQuery); err != nil { + log.Printf("telegram bot callback failed: %v", err) + } + continue + } + if update.Message == nil { + continue + } + if strconv.FormatInt(update.Message.Chat.ID, 10) != chatID { + continue + } + if err := b.handleMessage(ctx, token, chatID, update.Message); err != nil { + log.Printf("telegram bot command failed: %v", err) + } + } + } +} + +func (b *telegramBot) commandCredentials() (bool, string, string) { + if b == nil || b.settings == nil { + return false, "", "" + } + global := b.settings.snapshot() + token := strings.TrimSpace(global.TelegramBotToken) + chatID := strings.TrimSpace(global.TelegramChatID) + if token == "" || chatID == "" { + return false, token, chatID + } + return global.TelegramCommandsEnabled, token, chatID +} + +func (b *telegramBot) syncCommandMenu(ctx context.Context, token string, enabled bool, force bool) error { + if b == nil || b.server == nil || b.server.notifier == nil || b.server.notifier.client == nil { + return nil + } + token = strings.TrimSpace(token) + if token == "" { + return nil + } + state := "disabled" + if enabled { + state = "enabled:" + token + } + b.menuMu.Lock() + if !force && b.menuState == state { + b.menuMu.Unlock() + return nil + } + b.menuMu.Unlock() + var err error + if enabled { + err = b.server.notifier.setTelegramCommandMenu(ctx, token, telegramCommandMenu()) + } else { + err = b.server.notifier.deleteTelegramCommandMenu(ctx, token) + } + if err != nil { + return err + } + b.menuMu.Lock() + b.menuState = state + b.menuMu.Unlock() + return nil +} + +type telegramBotCommand struct { + Command string `json:"command"` + Description string `json:"description"` +} + +func telegramCommandMenu() []telegramBotCommand { + return []telegramBotCommand{ + {Command: "start", Description: "Show available commands"}, + {Command: "help", Description: "Show available commands"}, + {Command: "printers", Description: "List printers"}, + {Command: "status", Description: "Show printer status, temperatures, and fans"}, + {Command: "set", Description: "Set heater temperature"}, + {Command: "camera", Description: "Pick a camera and send a snapshot"}, + {Command: "print", Description: "Choose a recent file to print"}, + {Command: "jobs", Description: "List recent jobs"}, + {Command: "reprint", Description: "Restart the last print job"}, + } +} + +func (b *telegramBot) fetchUpdates(ctx context.Context, token string, offset int64) ([]telegramUpdate, error) { + endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/getUpdates", token) + form := url.Values{} + form.Set("timeout", "25") + form.Set("offset", strconv.FormatInt(offset, 10)) + form.Set("allowed_updates", `["message","callback_query"]`) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := b.client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return nil, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + detail := strings.TrimSpace(string(body)) + if detail != "" { + return nil, fmt.Errorf("telegram getUpdates failed: %s: %s", resp.Status, detail) + } + return nil, fmt.Errorf("telegram getUpdates failed: %s", resp.Status) + } + var parsed struct { + OK bool `json:"ok"` + Result []telegramUpdate `json:"result"` + } + if err := json.Unmarshal(body, &parsed); err != nil { + return nil, err + } + return parsed.Result, nil +} + +func (b *telegramBot) handleMessage(ctx context.Context, token, chatID string, msg *telegramMessage) error { + command, args := parseTelegramCommand(msg.Text) + if command == "" { + return nil + } + switch command { + case "start", "help": + return b.sendText(ctx, token, chatID, telegramHelpMessage()) + case "printers": + return b.sendText(ctx, token, chatID, b.buildPrintersMessage()) + case "status": + if strings.TrimSpace(args) == "" { + return b.sendPrinterSelection(ctx, token, chatID, "status") + } + printer, err := b.resolvePrinter(args) + if err != nil { + return b.sendText(ctx, token, chatID, err.Error()) + } + return b.sendPrinterStatus(ctx, token, chatID, printer) + case "camera": + if strings.TrimSpace(args) == "" { + return b.sendPrinterSelection(ctx, token, chatID, "camera") + } + printer, err := b.resolvePrinter(args) + if err != nil { + return b.sendText(ctx, token, chatID, err.Error()) + } + return b.sendCameraSelection(ctx, token, chatID, printer) + case "set": + printerQuery, heater, target, err := parseTelegramTemperatureSetArgs(args) + if err != nil { + return b.sendText(ctx, token, chatID, err.Error()) + } + if printerQuery == "" { + if printer, resolveErr := b.resolvePrinter(""); resolveErr == nil { + return b.sendTemperatureSetConfirmation(ctx, token, chatID, printer, telegramTemperatureSelection{ + PrinterID: printer.record.PrinterID, + Heater: heater, + Target: target, + CreatedAt: time.Now().UTC(), + }) + } + return b.sendTemperaturePrinterSelection(ctx, token, chatID, heater, target) + } + printer, err := b.resolvePrinter(printerQuery) + if err != nil { + return b.sendText(ctx, token, chatID, err.Error()) + } + return b.sendTemperatureSetConfirmation(ctx, token, chatID, printer, telegramTemperatureSelection{ + PrinterID: printer.record.PrinterID, + Heater: heater, + Target: target, + CreatedAt: time.Now().UTC(), + }) + case "print": + if strings.TrimSpace(args) == "" { + return b.sendPrinterSelection(ctx, token, chatID, "print") + } + printer, err := b.resolvePrinter(args) + if err != nil { + return b.sendText(ctx, token, chatID, err.Error()) + } + return b.sendPrintSelection(ctx, token, chatID, printer) + case "reprint", "restartlast", "restartjob": + if strings.TrimSpace(args) == "" { + return b.sendPrinterSelection(ctx, token, chatID, "reprint") + } + printer, err := b.resolvePrinter(args) + if err != nil { + return b.sendText(ctx, token, chatID, err.Error()) + } + return b.sendReprintConfirmation(ctx, token, chatID, printer) + case "jobs": + if strings.TrimSpace(args) == "" { + return b.sendPrinterSelection(ctx, token, chatID, "jobs") + } + printer, err := b.resolvePrinter(args) + if err != nil { + return b.sendText(ctx, token, chatID, err.Error()) + } + return b.sendJobHistory(ctx, token, chatID, printer) + default: + return b.sendText(ctx, token, chatID, telegramHelpMessage()) + } +} + +func (b *telegramBot) sendText(ctx context.Context, token, chatID, text string) error { + if strings.TrimSpace(text) == "" { + return nil + } + return b.server.notifier.sendTelegramMessage(ctx, token, chatID, text) +} + +func (b *telegramBot) sendPrinterSelection(ctx context.Context, token, chatID, command string) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + records := b.printerSelectionRecords() + if len(records) == 0 { + return b.sendText(ctx, token, chatID, "No printers are known yet.") + } + rows := make([][]map[string]string, 0, len(records)) + lines := []string{ + fmt.Sprintf("Select a printer for /%s:", command), + } + for _, record := range records { + name := strings.TrimSpace(record.DisplayName) + if name == "" { + name = record.PrinterID + } + rows = append(rows, []map[string]string{ + { + "text": truncateTelegramButtonLabel(name), + "callback_data": command + ":" + url.QueryEscape(record.PrinterID), + }, + }) + lines = append(lines, fmt.Sprintf("- %s (%s)", name, record.PrinterID)) + } + markup := map[string]any{ + "inline_keyboard": rows, + } + return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, strings.Join(lines, "\n"), markup) +} + +func (b *telegramBot) sendPrinterSnapshot(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error { + if printer.health == nil { + return b.sendText(ctx, token, chatID, b.buildPrinterStatusMessage(printer)) + } + snapshot, snapshotName, err := b.server.capturePrinterNotificationSnapshot(printer.record.PrinterID, printer.health) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nSnapshot unavailable: %v", b.buildPrinterStatusMessage(printer), err)) + } + caption := b.buildPrinterStatusMessage(printer) + if err := b.server.notifier.sendTelegramPhoto(ctx, token, chatID, caption, snapshot, snapshotName); err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nSnapshot send failed: %v", caption, err)) + } + return nil +} + +func (b *telegramBot) sendCameraSelection(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + cameras := snapshotCapableCameras(printer.health) + if len(cameras) == 0 { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nNo snapshot-capable cameras were found.", b.buildPrinterStatusMessage(printer))) + } + if len(cameras) == 1 { + return b.sendCameraSnapshot(ctx, token, chatID, printer, cameras[0].Name) + } + rows := make([][]map[string]string, 0, len(cameras)) + lines := []string{ + b.buildPrinterStatusMessage(printer), + "Select a camera to send a snapshot:", + } + for _, camera := range cameras { + name := strings.TrimSpace(camera.Name) + tokenID, err := b.storeCameraSelection(telegramCameraSelection{ + PrinterID: printer.record.PrinterID, + CameraName: name, + CreatedAt: time.Now().UTC(), + }) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nFailed to prepare camera selection: %v", b.buildPrinterStatusMessage(printer), err)) + } + rows = append(rows, []map[string]string{ + { + "text": truncateTelegramButtonLabel(name), + "callback_data": "camera-shot:" + tokenID, + }, + }) + lines = append(lines, fmt.Sprintf("- %s", name)) + } + return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, strings.Join(lines, "\n"), map[string]any{"inline_keyboard": rows}) +} + +func (b *telegramBot) sendCameraSnapshot(ctx context.Context, token, chatID string, printer telegramPrinterTarget, cameraName string) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + cameraName = strings.TrimSpace(cameraName) + if cameraName == "" { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nSnapshot unavailable: no camera selected.", b.buildPrinterStatusMessage(printer))) + } + if printer.health == nil { + return b.sendText(ctx, token, chatID, b.buildPrinterStatusMessage(printer)) + } + snapshot, snapshotName, err := b.server.capturePrinterNotificationSnapshotWithCamera(printer.record.PrinterID, printer.health, cameraName) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nSnapshot unavailable: %v", b.buildPrinterStatusMessage(printer), err)) + } + caption := b.buildPrinterStatusMessage(printer) + if err := b.server.notifier.sendTelegramPhoto(ctx, token, chatID, caption, snapshot, snapshotName); err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nSnapshot send failed: %v", caption, err)) + } + return nil +} + +func (b *telegramBot) sendPrinterStatus(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + message := b.buildPrinterStatusMessage(printer) + if liveStatus := printerLiveStatus(printer.health); len(liveStatus) > 0 { + detailed := b.buildPrinterStatusMessageWithLiveData(printer, liveStatus) + return b.sendText(ctx, token, chatID, detailed) + } + t := b.server.tunnelForPrinter(printer.record.PrinterID) + if t == nil { + return b.sendText(ctx, token, chatID, message) + } + objects := liveObjectQueryNames() + log.Printf("telegram status live query printer_id=%s objects=%v", printer.record.PrinterID, objects) + status, err := b.server.fetchPrinterObjectStatus(ctx, t, objects) + if err != nil { + log.Printf("telegram status live query failed printer_id=%s error=%v", printer.record.PrinterID, err) + return b.sendText(ctx, token, chatID, message) + } + detailed := b.buildPrinterStatusMessageWithLiveData(printer, status) + return b.sendText(ctx, token, chatID, detailed) +} + +func printerLiveStatus(health *protocol.Health) map[string]any { + if health == nil || health.PrintStatus == nil { + return nil + } + status := health.PrintStatus.MoonrakerStatus + if len(status) == 0 { + return nil + } + return status +} + +func (b *telegramBot) sendTemperaturePrinterSelection(ctx context.Context, token, chatID, heater string, target float64) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + records := b.printerSelectionRecords() + if len(records) == 0 { + return b.sendText(ctx, token, chatID, "No printers are known yet.") + } + selectionID, err := b.storeTemperatureSelection(telegramTemperatureSelection{ + Heater: heater, + Target: target, + CreatedAt: time.Now().UTC(), + }) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("Failed to prepare temperature selection: %v", err)) + } + rows := make([][]map[string]string, 0, len(records)) + lines := []string{fmt.Sprintf("Select a printer for /set %s %.1f:", temperatureHeaterDisplayName(heater), target)} + for _, record := range records { + name := strings.TrimSpace(record.DisplayName) + if name == "" { + name = record.PrinterID + } + rows = append(rows, []map[string]string{ + { + "text": truncateTelegramButtonLabel(name), + "callback_data": "set-temp:" + selectionID + ":" + url.QueryEscape(record.PrinterID), + }, + }) + lines = append(lines, fmt.Sprintf("- %s (%s)", name, record.PrinterID)) + } + return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, strings.Join(lines, "\n"), map[string]any{"inline_keyboard": rows}) +} + +func (b *telegramBot) sendTemperatureSetConfirmation(ctx context.Context, token, chatID string, printer telegramPrinterTarget, selection telegramTemperatureSelection) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + message := b.buildPrinterStatusMessage(printer) + if mode := strings.ToLower(strings.TrimSpace(printer.record.ControlMode)); mode == "readonly" { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nTemperature set unavailable: printer control mode is read-only.", message)) + } + t := b.server.tunnelForPrinter(printer.record.PrinterID) + if t == nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nTemperature set unavailable: printer is not connected.", message)) + } + heaterName, err := normalizeTemperatureHeater(selection.Heater) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nTemperature set unavailable: %v", message, err)) + } + if selection.Target < 0 { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nTemperature set unavailable: target temperature must be non-negative.", message)) + } + selection.Heater = heaterName + selection.PrinterID = printer.record.PrinterID + tokenID, err := b.storeTemperatureSelection(selection) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nTemperature confirmation unavailable: %v", message, err)) + } + if printer.health == nil { + printer.health = &protocol.Health{} + } + snapshot, snapshotName, err := b.server.capturePrinterNotificationSnapshot(printer.record.PrinterID, printer.health) + caption := b.buildTemperatureConfirmationMessage(printer, selection) + markup := map[string]any{ + "inline_keyboard": [][]map[string]string{ + { + { + "text": "Set temperature", + "callback_data": "temp-confirm:" + tokenID, + }, + { + "text": "Cancel", + "callback_data": "temp-cancel:" + tokenID, + }, + }, + }, + } + if err == nil && len(snapshot) > 0 { + return b.server.notifier.sendTelegramPhotoWithMarkup(ctx, token, chatID, caption, snapshot, snapshotName, markup) + } + return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, caption, markup) +} + +func (b *telegramBot) startSelectedTemperatureSet(ctx context.Context, token, chatID, callbackID string, printer telegramPrinterTarget, selection telegramTemperatureSelection) error { + if selection.PrinterID == "" { + return b.answerCallbackQuery(ctx, token, callbackID, "This temperature selection is no longer available.") + } + t := b.server.tunnelForPrinter(selection.PrinterID) + if t == nil { + return b.answerCallbackQuery(ctx, token, callbackID, "The printer is no longer connected.") + } + if mode := strings.ToLower(strings.TrimSpace(printer.record.ControlMode)); mode == "readonly" { + return b.answerCallbackQuery(ctx, token, callbackID, "Printer control mode is read-only.") + } + if err := b.server.setPrinterHeaterTarget(ctx, t, selection.Heater, selection.Target); err != nil { + return b.answerCallbackQuery(ctx, token, callbackID, fmt.Sprintf("Failed to set %s to %.1fยฐC: %v", temperatureHeaterDisplayName(selection.Heater), selection.Target, err)) + } + if err := b.answerCallbackQuery(ctx, token, callbackID, "Setting heater target..."); err != nil { + return err + } + name := strings.TrimSpace(printer.record.DisplayName) + if name == "" { + name = printer.record.PrinterID + } + return b.sendText(ctx, token, chatID, fmt.Sprintf("Printer: %s\nEvent: Set %s target\nTarget: %.1fยฐC", name, temperatureHeaterDisplayName(selection.Heater), selection.Target)) +} + +func (b *telegramBot) sendReprintConfirmation(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + if printer.health == nil || printer.health.PrintStatus == nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: printer is not connected.", b.buildPrinterStatusMessage(printer))) + } + currentState := strings.ToLower(strings.TrimSpace(printer.health.PrintStatus.State)) + switch currentState { + case "printing", "paused": + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: printer is currently %s.", b.buildPrinterStatusMessage(printer), currentState)) + } + if mode := strings.ToLower(strings.TrimSpace(printer.record.ControlMode)); mode == "readonly" { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: printer control mode is read-only.", b.buildPrinterStatusMessage(printer))) + } + t := b.server.tunnelForPrinter(printer.record.PrinterID) + if t == nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: printer is not connected.", b.buildPrinterStatusMessage(printer))) + } + filename, historyStatus, err := b.server.lastPrintableJobFilename(ctx, t) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: %v", b.buildPrinterStatusMessage(printer), err)) + } + if filename == "" { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: no recent printable job was found.", b.buildPrinterStatusMessage(printer))) + } + selection := telegramPrintSelection{ + PrinterID: printer.record.PrinterID, + Filename: filename, + Label: filename, + CreatedAt: time.Now().UTC(), + } + tokenID, err := b.storeSelection(selection) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: %v", b.buildPrinterStatusMessage(printer), err)) + } + selectionToken := tokenID + selection.Label = formatJobSelectionLabel(filename, historyStatus) + return b.sendReprintConfirmationWithToken(ctx, token, chatID, printer, selection, selectionToken) +} + +func (b *telegramBot) handleCallbackQuery(ctx context.Context, token, chatID string, query *telegramCallbackQuery) error { + if query == nil { + return nil + } + action := parseTelegramCallbackAction(strings.TrimSpace(query.Data)) + switch action.Kind { + case "status": + record, ok := b.printerRecordFromCallback(action.ID) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.") + } + if err := b.answerCallbackQuery(ctx, token, query.ID, "Loading printer status."); err != nil { + return err + } + return b.sendPrinterStatus(ctx, token, chatID, b.resolvePrinterByRecord(record)) + case "print": + record, ok := b.printerRecordFromCallback(action.ID) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.") + } + if err := b.answerCallbackQuery(ctx, token, query.ID, "Loading recent jobs."); err != nil { + return err + } + return b.sendPrintSelection(ctx, token, chatID, b.resolvePrinterByRecord(record)) + case "reprint": + record, ok := b.printerRecordFromCallback(action.ID) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.") + } + if err := b.answerCallbackQuery(ctx, token, query.ID, "Preparing confirmation."); err != nil { + return err + } + return b.sendReprintConfirmation(ctx, token, chatID, b.resolvePrinterByRecord(record)) + case "jobs": + record, ok := b.printerRecordFromCallback(action.ID) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.") + } + if err := b.answerCallbackQuery(ctx, token, query.ID, "Loading recent jobs."); err != nil { + return err + } + return b.sendJobHistory(ctx, token, chatID, b.resolvePrinterByRecord(record)) + case "camera": + record, ok := b.printerRecordFromCallback(action.ID) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.") + } + if err := b.answerCallbackQuery(ctx, token, query.ID, "Loading cameras."); err != nil { + return err + } + return b.sendCameraSelection(ctx, token, chatID, b.resolvePrinterByRecord(record)) + case "set-temp": + parts := strings.SplitN(action.ID, ":", 2) + if len(parts) != 2 { + return b.answerCallbackQuery(ctx, token, query.ID, "This temperature selection expired.") + } + selection, ok := b.consumeTemperatureSelection(parts[0]) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This temperature selection expired.") + } + printerID, err := url.QueryUnescape(parts[1]) + if err != nil { + return b.answerCallbackQuery(ctx, token, query.ID, "This temperature selection expired.") + } + record, ok := b.printerRecordFromCallback(printerID) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.") + } + if err := b.answerCallbackQuery(ctx, token, query.ID, "Preparing heater confirmation."); err != nil { + return err + } + selection.PrinterID = record.PrinterID + return b.sendTemperatureSetConfirmation(ctx, token, chatID, b.resolvePrinterByRecord(record), selection) + case "temp-confirm": + selection, ok := b.consumeTemperatureSelection(action.ID) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This temperature selection expired.") + } + record, ok := b.server.printerSettings.snapshot(selection.PrinterID) + if !ok || record.PrinterID == "" { + record = printerSettingsRecord{PrinterID: selection.PrinterID} + } + printer := b.resolvePrinterByRecord(record) + if err := b.startSelectedTemperatureSet(ctx, token, chatID, query.ID, printer, selection); err != nil { + return err + } + if query.Message != nil { + _ = b.server.notifier.deleteTelegramMessage(ctx, token, chatID, query.Message.MessageID) + } + return nil + case "temp-cancel": + if _, ok := b.consumeTemperatureSelection(action.ID); !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This temperature selection expired.") + } + if err := b.answerCallbackQuery(ctx, token, query.ID, "Cancelled."); err != nil { + return err + } + if query.Message != nil { + _ = b.server.notifier.deleteTelegramMessage(ctx, token, chatID, query.Message.MessageID) + } + return nil + case "camera-shot": + selection, ok := b.consumeCameraSelection(action.ID) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This camera selection expired.") + } + record, ok := b.server.printerSettings.snapshot(selection.PrinterID) + if !ok || record.PrinterID == "" { + record = printerSettingsRecord{PrinterID: selection.PrinterID} + } + printer := b.resolvePrinterByRecord(record) + if err := b.answerCallbackQuery(ctx, token, query.ID, "Sending snapshot."); err != nil { + return err + } + return b.sendCameraSnapshot(ctx, token, chatID, printer, selection.CameraName) + case "select": + selection, ok := b.peekSelection(action.ID) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This print selection expired.") + } + record, _ := b.server.printerSettings.snapshot(selection.PrinterID) + if record.PrinterID == "" { + record = printerSettingsRecord{PrinterID: selection.PrinterID} + } + printer := b.resolvePrinterByRecord(record) + if err := b.sendPrintConfirmation(ctx, token, chatID, printer, selection); err != nil { + return err + } + if err := b.answerCallbackQuery(ctx, token, query.ID, "Review the snapshot below."); err != nil { + return err + } + _, _ = b.consumeSelection(action.ID) + return nil + case "confirm": + selection, ok := b.consumeSelection(action.ID) + if !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This print selection expired.") + } + record, _ := b.server.printerSettings.snapshot(selection.PrinterID) + if record.PrinterID == "" { + record = printerSettingsRecord{PrinterID: selection.PrinterID} + } + printer := b.resolvePrinterByRecord(record) + if err := b.startSelectedPrint(ctx, token, chatID, query.ID, printer, selection); err != nil { + return err + } + if query.Message != nil { + _ = b.server.notifier.deleteTelegramMessage(ctx, token, chatID, query.Message.MessageID) + } + return nil + case "cancel": + if _, ok := b.consumeSelection(action.ID); !ok { + return b.answerCallbackQuery(ctx, token, query.ID, "This print selection expired.") + } + if err := b.answerCallbackQuery(ctx, token, query.ID, "Cancelled."); err != nil { + return err + } + if query.Message != nil { + _ = b.server.notifier.deleteTelegramMessage(ctx, token, chatID, query.Message.MessageID) + } + return nil + default: + return b.answerCallbackQuery(ctx, token, query.ID, "This action is no longer available.") + } +} + +func (b *telegramBot) sendPrintSelection(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + t := b.server.tunnelForPrinter(printer.record.PrinterID) + if t == nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint selection unavailable: printer is not connected.", b.buildPrinterStatusMessage(printer))) + } + jobs, err := b.server.fetchPrinterJobHistory(ctx, t) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint selection unavailable: %v", b.buildPrinterStatusMessage(printer), err)) + } + summaries := selectPrintableJobs(jobs, 5) + if len(summaries) == 0 { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nNo recent printable jobs were found.", b.buildPrinterStatusMessage(printer))) + } + rows := make([][]map[string]string, 0, len(summaries)) + lines := []string{ + b.buildPrinterStatusMessage(printer), + "Select a job to review before printing:", + } + for _, job := range summaries { + tokenID, err := b.storeSelection(telegramPrintSelection{ + PrinterID: printer.record.PrinterID, + Filename: job.Filename, + Label: job.Label, + CreatedAt: time.Now().UTC(), + }) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nFailed to prepare print selection: %v", b.buildPrinterStatusMessage(printer), err)) + } + rows = append(rows, []map[string]string{ + { + "text": job.ButtonLabel, + "callback_data": "select:" + tokenID, + }, + }) + lines = append(lines, fmt.Sprintf("- %s", job.Label)) + } + markup := map[string]any{ + "inline_keyboard": rows, + } + return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, strings.Join(lines, "\n"), markup) +} + +func (b *telegramBot) sendJobHistory(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + t := b.server.tunnelForPrinter(printer.record.PrinterID) + if t == nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nJob history unavailable: printer is not connected.", b.buildPrinterStatusMessage(printer))) + } + jobs, err := b.server.fetchPrinterJobHistory(ctx, t) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nJob history unavailable: %v", b.buildPrinterStatusMessage(printer), err)) + } + if len(jobs) == 0 { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nNo recent jobs were found.", b.buildPrinterStatusMessage(printer))) + } + return b.sendText(ctx, token, chatID, strings.Join(buildJobHistoryLines(b.buildPrinterStatusMessage(printer), jobs), "\n")) +} + +func buildJobHistoryLines(header string, jobs []map[string]any) []string { + lines := []string{ + header, + "Recent jobs:", + } + for _, job := range jobs { + filename := strings.TrimSpace(stringFromAny(job["filename"])) + if filename == "" { + continue + } + status := strings.TrimSpace(stringFromAny(job["status"])) + if status != "" { + lines = append(lines, fmt.Sprintf("- %s (%s)", filename, status)) + continue + } + lines = append(lines, fmt.Sprintf("- %s", filename)) + } + if len(lines) == 2 { + lines = append(lines, "- No printable job entries were found.") + } + return lines +} + +func (b *telegramBot) sendPrintConfirmation(ctx context.Context, token, chatID string, printer telegramPrinterTarget, selection telegramPrintSelection) error { + if selection.PrinterID == "" || selection.Filename == "" { + return b.sendText(ctx, token, chatID, "This print selection is no longer available.") + } + return b.sendPrintConfirmationWithToken(ctx, token, chatID, printer, selection, "", "select") +} + +func (b *telegramBot) sendPrintConfirmationWithToken(ctx context.Context, token, chatID string, printer telegramPrinterTarget, selection telegramPrintSelection, selectionToken string, source string) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + if printer.health == nil { + printer.health = &protocol.Health{} + } + snapshot, snapshotName, err := b.server.capturePrinterNotificationSnapshot(printer.record.PrinterID, printer.health) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint confirmation unavailable: %v", b.buildPrinterStatusMessage(printer), err)) + } + caption := b.buildPrintConfirmationMessage(printer, selection, source) + if selectionToken == "" { + tokenID, err := b.storeSelection(selection) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint confirmation unavailable: %v", b.buildPrinterStatusMessage(printer), err)) + } + selectionToken = tokenID + } + markup := map[string]any{ + "inline_keyboard": [][]map[string]string{ + { + { + "text": "Confirm", + "callback_data": "confirm:" + selectionToken, + }, + { + "text": "Cancel", + "callback_data": "cancel:" + selectionToken, + }, + }, + }, + } + if len(snapshot) > 0 { + return b.server.notifier.sendTelegramPhotoWithMarkup(ctx, token, chatID, caption, snapshot, snapshotName, markup) + } + return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, caption, markup) +} + +func (b *telegramBot) sendReprintConfirmationWithToken(ctx context.Context, token, chatID string, printer telegramPrinterTarget, selection telegramPrintSelection, selectionToken string) error { + if b == nil || b.server == nil { + return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.") + } + if printer.health == nil { + printer.health = &protocol.Health{} + } + snapshot, snapshotName, err := b.server.capturePrinterNotificationSnapshot(printer.record.PrinterID, printer.health) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint confirmation unavailable: %v", b.buildPrinterStatusMessage(printer), err)) + } + caption := b.buildReprintConfirmationMessage(printer, selection) + if selectionToken == "" { + tokenID, err := b.storeSelection(selection) + if err != nil { + return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint confirmation unavailable: %v", b.buildPrinterStatusMessage(printer), err)) + } + selectionToken = tokenID + } + markup := map[string]any{ + "inline_keyboard": [][]map[string]string{ + { + { + "text": "Confirm", + "callback_data": "confirm:" + selectionToken, + }, + { + "text": "Cancel", + "callback_data": "cancel:" + selectionToken, + }, + }, + }, + } + if len(snapshot) > 0 { + return b.server.notifier.sendTelegramPhotoWithMarkup(ctx, token, chatID, caption, snapshot, snapshotName, markup) + } + return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, caption, markup) +} + +func (b *telegramBot) startSelectedPrint(ctx context.Context, token, chatID, callbackID string, printer telegramPrinterTarget, selection telegramPrintSelection) error { + if selection.PrinterID == "" || selection.Filename == "" { + return b.answerCallbackQuery(ctx, token, callbackID, "This print selection is no longer available.") + } + t := b.server.tunnelForPrinter(selection.PrinterID) + if t == nil { + return b.answerCallbackQuery(ctx, token, callbackID, "The printer is no longer connected.") + } + if err := b.server.startPrinterJob(ctx, t, selection.Filename); err != nil { + return b.answerCallbackQuery(ctx, token, callbackID, fmt.Sprintf("Failed to start %s: %v", selection.Label, err)) + } + if err := b.answerCallbackQuery(ctx, token, callbackID, "Starting print..."); err != nil { + return err + } + name := strings.TrimSpace(printer.record.DisplayName) + if name == "" { + name = printer.record.PrinterID + } + return b.sendText(ctx, token, chatID, fmt.Sprintf("Printer: %s\nEvent: Started print job\nFile: %s", name, selection.Filename)) +} + +func (b *telegramBot) answerCallbackQuery(ctx context.Context, token, callbackID, text string) error { + endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/answerCallbackQuery", token) + form := url.Values{} + form.Set("callback_query_id", callbackID) + if text = strings.TrimSpace(text); text != "" { + form.Set("text", text) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := b.server.notifier.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + detail := strings.TrimSpace(string(body)) + if detail != "" { + return fmt.Errorf("telegram answerCallbackQuery failed: %s: %s", resp.Status, detail) + } + return fmt.Errorf("telegram answerCallbackQuery failed: %s", resp.Status) + } + return nil +} + +func (b *telegramBot) storeSelection(selection telegramPrintSelection) (string, error) { + id, err := newID() + if err != nil { + return "", err + } + b.mu.Lock() + defer b.mu.Unlock() + if b.selections == nil { + b.selections = make(map[string]telegramPrintSelection) + } + b.pruneSelectionsLocked() + b.selections[id] = selection + return id, nil +} + +func (b *telegramBot) storeCameraSelection(selection telegramCameraSelection) (string, error) { + id, err := newID() + if err != nil { + return "", err + } + b.mu.Lock() + defer b.mu.Unlock() + if b.cameraSelections == nil { + b.cameraSelections = make(map[string]telegramCameraSelection) + } + b.pruneCameraSelectionsLocked() + b.cameraSelections[id] = selection + return id, nil +} + +func (b *telegramBot) storeTemperatureSelection(selection telegramTemperatureSelection) (string, error) { + id, err := newID() + if err != nil { + return "", err + } + b.mu.Lock() + defer b.mu.Unlock() + if b.temperatureSelections == nil { + b.temperatureSelections = make(map[string]telegramTemperatureSelection) + } + b.pruneTemperatureSelectionsLocked() + b.temperatureSelections[id] = selection + return id, nil +} + +func (b *telegramBot) peekSelection(id string) (telegramPrintSelection, bool) { + b.mu.Lock() + defer b.mu.Unlock() + if b.selections == nil { + return telegramPrintSelection{}, false + } + b.pruneSelectionsLocked() + selection, ok := b.selections[id] + return selection, ok +} + +func (b *telegramBot) consumeSelection(id string) (telegramPrintSelection, bool) { + b.mu.Lock() + defer b.mu.Unlock() + if b.selections == nil { + return telegramPrintSelection{}, false + } + b.pruneSelectionsLocked() + selection, ok := b.selections[id] + if ok { + delete(b.selections, id) + } + return selection, ok +} + +func (b *telegramBot) consumeCameraSelection(id string) (telegramCameraSelection, bool) { + b.mu.Lock() + defer b.mu.Unlock() + if b.cameraSelections == nil { + return telegramCameraSelection{}, false + } + b.pruneCameraSelectionsLocked() + selection, ok := b.cameraSelections[id] + if ok { + delete(b.cameraSelections, id) + } + return selection, ok +} + +func (b *telegramBot) consumeTemperatureSelection(id string) (telegramTemperatureSelection, bool) { + b.mu.Lock() + defer b.mu.Unlock() + if b.temperatureSelections == nil { + return telegramTemperatureSelection{}, false + } + b.pruneTemperatureSelectionsLocked() + selection, ok := b.temperatureSelections[id] + if !ok { + return telegramTemperatureSelection{}, false + } + delete(b.temperatureSelections, id) + return selection, true +} + +func (b *telegramBot) pruneSelectionsLocked() { + if len(b.selections) == 0 { + return + } + now := time.Now().UTC() + for id, selection := range b.selections { + if now.Sub(selection.CreatedAt) > 15*time.Minute { + delete(b.selections, id) + } + } +} + +func (b *telegramBot) pruneCameraSelectionsLocked() { + if len(b.cameraSelections) == 0 { + return + } + now := time.Now().UTC() + for id, selection := range b.cameraSelections { + if now.Sub(selection.CreatedAt) > 15*time.Minute { + delete(b.cameraSelections, id) + } + } +} + +func (b *telegramBot) pruneTemperatureSelectionsLocked() { + if len(b.temperatureSelections) == 0 { + return + } + now := time.Now().UTC() + for id, selection := range b.temperatureSelections { + if now.Sub(selection.CreatedAt) > 15*time.Minute { + delete(b.temperatureSelections, id) + } + } +} + +func selectPrintableJobs(jobs []map[string]any, limit int) []telegramPrintableJob { + if limit <= 0 { + limit = 5 + } + out := make([]telegramPrintableJob, 0, limit) + for _, job := range jobs { + filename := strings.TrimSpace(stringFromAny(job["filename"])) + if filename == "" { + continue + } + status := strings.ToLower(strings.TrimSpace(stringFromAny(job["status"]))) + if status != "" && !isTerminalJobHistoryStatus(status) { + continue + } + label := filename + if status != "" { + label = fmt.Sprintf("%s (%s)", filename, status) + } + out = append(out, telegramPrintableJob{ + Filename: filename, + Label: label, + ButtonLabel: truncateTelegramButtonLabel(filename), + }) + if len(out) >= limit { + break + } + } + return out +} + +type telegramPrintableFile struct { + Path string + Label string + ButtonLabel string +} + +type telegramLiveObjectSummary struct { + Label string + Line string +} + +func selectPrintableFiles(files []moonrakerFileInfo, limit int) []telegramPrintableFile { + if limit <= 0 { + limit = 5 + } + sorted := make([]moonrakerFileInfo, 0, len(files)) + for _, file := range files { + path := strings.TrimSpace(file.Path) + if path == "" { + continue + } + sorted = append(sorted, file) + } + sort.SliceStable(sorted, func(i, j int) bool { + if sorted[i].Modified == sorted[j].Modified { + return strings.ToLower(strings.TrimSpace(sorted[i].Path)) < strings.ToLower(strings.TrimSpace(sorted[j].Path)) + } + return sorted[i].Modified > sorted[j].Modified + }) + out := make([]telegramPrintableFile, 0, limit) + for _, file := range sorted { + filePath := strings.TrimSpace(file.Path) + if filePath == "" { + continue + } + label := filePath + out = append(out, telegramPrintableFile{ + Path: filePath, + Label: label, + ButtonLabel: truncateTelegramButtonLabel(path.Base(filePath)), + }) + if len(out) >= limit { + break + } + } + return out +} + +func liveObjectQueryNames() []string { + return []string{ + "extruder", + "extruder1", + "extruder2", + "heater_bed", + "heater_generic", + "temperature_sensor chamber", + "temperature_sensor", + "temperature_fan", + "temperature_fan chamber", + "fan", + "fan_generic", + "controller_fan", + } +} + +func temperatureObjectSummary(status map[string]any) []string { + summaries := summarizeLiveObjects(status, func(name string, obj map[string]any) (string, bool) { + temp, ok := numberFromAny(obj["temperature"]) + if !ok { + return "", false + } + line := fmt.Sprintf("%s: %.1fยฐC", name, temp) + if target, ok := numberFromAny(obj["target"]); ok && target > 0 { + line += fmt.Sprintf(" / %.1fยฐC", target) + } + return line, true + }) + return summaries +} + +func fanObjectSummary(status map[string]any) []string { + return summarizeLiveObjects(status, func(name string, obj map[string]any) (string, bool) { + speed, ok := numberFromAny(obj["speed"]) + if !ok { + return "", false + } + line := fmt.Sprintf("%s: %.0f%%", name, speed*100) + if rpm, ok := numberFromAny(obj["rpm"]); ok && rpm > 0 { + line += fmt.Sprintf(" (%d rpm)", int64(rpm)) + } + return line, true + }) +} + +func summarizeLiveObjects(status map[string]any, formatter func(string, map[string]any) (string, bool)) []string { + if len(status) == 0 { + return nil + } + type item struct { + name string + line string + } + items := make([]item, 0, len(status)) + for name, value := range status { + obj, ok := value.(map[string]any) + if !ok { + continue + } + if strings.EqualFold(name, "print_stats") || strings.EqualFold(name, "display_status") || strings.EqualFold(name, "gcode_move") || strings.EqualFold(name, "toolhead") { + continue + } + line, ok := formatter(name, obj) + if !ok || strings.TrimSpace(line) == "" { + continue + } + items = append(items, item{name: strings.ToLower(strings.TrimSpace(name)), line: line}) + } + sort.SliceStable(items, func(i, j int) bool { + return items[i].name < items[j].name + }) + lines := make([]string, 0, len(items)) + for _, item := range items { + lines = append(lines, "- "+item.line) + } + return lines +} + +func numberFromAny(value any) (float64, bool) { + switch v := value.(type) { + case float64: + return v, true + case float32: + return float64(v), true + case int: + return float64(v), true + case int64: + return float64(v), true + case json.Number: + f, err := v.Float64() + return f, err == nil + default: + return 0, false + } +} + +func snapshotCapableCameras(health *protocol.Health) []protocol.CameraHealth { + if health == nil { + return nil + } + cameras := make([]protocol.CameraHealth, 0, len(health.Cameras)) + for _, camera := range health.Cameras { + if strings.TrimSpace(camera.Name) == "" || !camera.HasSnapshot { + continue + } + cameras = append(cameras, camera) + } + sort.SliceStable(cameras, func(i, j int) bool { + return strings.ToLower(strings.TrimSpace(cameras[i].Name)) < strings.ToLower(strings.TrimSpace(cameras[j].Name)) + }) + return cameras +} + +func splitCameraCallbackID(value string) (string, string, bool) { + value = strings.TrimSpace(value) + if value == "" { + return "", "", false + } + decoded, err := url.QueryUnescape(value) + if err != nil { + decoded = value + } + printerID, cameraName, ok := strings.Cut(decoded, "|") + if !ok { + return "", "", false + } + printerID = strings.TrimSpace(printerID) + cameraName = strings.TrimSpace(cameraName) + if printerID == "" || cameraName == "" { + return "", "", false + } + return printerID, cameraName, true +} + +func truncateTelegramButtonLabel(value string) string { + value = strings.TrimSpace(value) + if value == "" { + return "print" + } + runes := []rune(value) + if len(runes) <= 24 { + return value + } + return string(runes[:24]) + "..." +} + +func parseTelegramCallbackAction(data string) telegramCallbackAction { + data = strings.TrimSpace(data) + if data == "" { + return telegramCallbackAction{} + } + kind, id, ok := strings.Cut(data, ":") + if !ok { + return telegramCallbackAction{} + } + decodedID, err := url.QueryUnescape(strings.TrimSpace(id)) + if err != nil { + decodedID = strings.TrimSpace(id) + } + return telegramCallbackAction{Kind: strings.ToLower(strings.TrimSpace(kind)), ID: decodedID} +} + +func (b *telegramBot) buildPrintConfirmationMessage(printer telegramPrinterTarget, selection telegramPrintSelection, source string) string { + name := strings.TrimSpace(printer.record.DisplayName) + if name == "" { + name = printer.record.PrinterID + } + lines := []string{ + fmt.Sprintf("Printer: %s", name), + "Action: Start print", + fmt.Sprintf("File: %s", selection.Filename), + "Snapshot: review the bed before confirming", + } + if source == "print" { + lines[3] = "Snapshot: review the printer before confirming" + } + if selection.Label != "" && selection.Label != selection.Filename { + lines = append(lines, fmt.Sprintf("Selection: %s", selection.Label)) + } + if printer.health != nil && printer.health.PrintStatus != nil { + if state := strings.TrimSpace(printer.health.PrintStatus.State); state != "" { + lines = append(lines, fmt.Sprintf("Current state: %s", state)) + } + } + return strings.Join(lines, "\n") +} + +func (b *telegramBot) buildReprintConfirmationMessage(printer telegramPrinterTarget, selection telegramPrintSelection) string { + name := strings.TrimSpace(printer.record.DisplayName) + if name == "" { + name = printer.record.PrinterID + } + lines := []string{ + fmt.Sprintf("Printer: %s", name), + "Action: Reprint last job", + fmt.Sprintf("File: %s", selection.Filename), + "Snapshot: review the bed before confirming", + } + if selection.Label != "" && selection.Label != selection.Filename { + lines = append(lines, fmt.Sprintf("Selection: %s", selection.Label)) + } + if printer.health != nil && printer.health.PrintStatus != nil { + if state := strings.TrimSpace(printer.health.PrintStatus.State); state != "" { + lines = append(lines, fmt.Sprintf("Current state: %s", state)) + } + } + return strings.Join(lines, "\n") +} + +func (b *telegramBot) buildTemperatureConfirmationMessage(printer telegramPrinterTarget, selection telegramTemperatureSelection) string { + name := strings.TrimSpace(printer.record.DisplayName) + if name == "" { + name = printer.record.PrinterID + } + heater := temperatureHeaterDisplayName(selection.Heater) + lines := []string{ + fmt.Sprintf("Printer: %s", name), + fmt.Sprintf("Action: Set %s target", heater), + fmt.Sprintf("Target: %s %.1fยฐC", heater, selection.Target), + "Snapshot: review the bed before confirming", + } + if printer.health != nil && printer.health.PrintStatus != nil { + if state := strings.TrimSpace(printer.health.PrintStatus.State); state != "" { + lines = append(lines, fmt.Sprintf("Current state: %s", state)) + } + } + return strings.Join(lines, "\n") +} + +func formatJobSelectionLabel(filename, status string) string { + filename = strings.TrimSpace(filename) + status = strings.TrimSpace(status) + if filename == "" { + return "" + } + if status == "" { + return filename + } + return fmt.Sprintf("%s (%s)", filename, status) +} + +type telegramPrinterTarget struct { + record printerSettingsRecord + health *protocol.Health +} + +func (b *telegramBot) resolvePrinter(query string) (telegramPrinterTarget, error) { + query = strings.TrimSpace(query) + records := b.server.printerSettings.list() + if query == "" { + if len(records) == 1 { + return b.resolvePrinterByRecord(records[0]), nil + } + connected := b.connectedPrinters() + if len(connected) == 1 { + return connected[0], nil + } + if len(records) == 0 { + return telegramPrinterTarget{}, fmt.Errorf("no printers are known yet") + } + return telegramPrinterTarget{}, fmt.Errorf("specify a printer id, for example: /status %s", records[0].PrinterID) + } + for _, record := range records { + if strings.EqualFold(record.PrinterID, query) || strings.EqualFold(record.DisplayName, query) { + return b.resolvePrinterByRecord(record), nil + } + } + return telegramPrinterTarget{}, fmt.Errorf("unknown printer %q", query) +} + +func (b *telegramBot) resolvePrinterByRecord(record printerSettingsRecord) telegramPrinterTarget { + target := telegramPrinterTarget{record: record} + b.server.tunnelsMu.RLock() + t := b.server.tunnels[record.PrinterID] + b.server.tunnelsMu.RUnlock() + if t != nil { + t.healthMu.RLock() + target.health = t.health + t.healthMu.RUnlock() + } + if target.health == nil { + target.health = &protocol.Health{} + } + return target +} + +func (b *telegramBot) connectedPrinters() []telegramPrinterTarget { + b.server.tunnelsMu.RLock() + defer b.server.tunnelsMu.RUnlock() + targets := make([]telegramPrinterTarget, 0, len(b.server.tunnels)) + for printerID, t := range b.server.tunnels { + record, ok := b.server.printerSettings.snapshot(printerID) + if !ok { + record = printerSettingsRecord{PrinterID: printerID} + } + target := telegramPrinterTarget{record: record} + if t != nil { + t.healthMu.RLock() + target.health = t.health + t.healthMu.RUnlock() + } + targets = append(targets, target) + } + return targets +} + +func (b *telegramBot) printerSelectionRecords() []printerSettingsRecord { + if b == nil || b.server == nil { + return nil + } + records := b.server.printerSettings.list() + seen := make(map[string]struct{}, len(records)) + out := make([]printerSettingsRecord, 0, len(records)) + for _, record := range records { + printerID := strings.TrimSpace(record.PrinterID) + if printerID == "" { + continue + } + seen[printerID] = struct{}{} + out = append(out, record) + } + for _, target := range b.connectedPrinters() { + printerID := strings.TrimSpace(target.record.PrinterID) + if printerID == "" { + continue + } + if _, ok := seen[printerID]; ok { + continue + } + seen[printerID] = struct{}{} + out = append(out, target.record) + } + sort.SliceStable(out, func(i, j int) bool { + return strings.ToLower(strings.TrimSpace(out[i].PrinterID)) < strings.ToLower(strings.TrimSpace(out[j].PrinterID)) + }) + return out +} + +func (b *telegramBot) printerRecordFromCallback(printerID string) (printerSettingsRecord, bool) { + printerID = strings.TrimSpace(printerID) + if printerID == "" || b == nil || b.server == nil || b.server.printerSettings == nil { + return printerSettingsRecord{}, false + } + record, ok := b.server.printerSettings.snapshot(printerID) + if !ok { + return printerSettingsRecord{}, false + } + return record, true +} + +func telegramHelpMessage() string { + return strings.Join([]string{ + "Commands:", + "/help - show this message", + "/printers - list known printers", + "/status [printer] - show the current print status, temperatures, and fans", + "/set [printer] - set a heater target", + "/print [printer] - list recent jobs and choose one to print", + "/jobs [printer] - list recent jobs", + "/camera [printer] - pick a camera and send a snapshot", + "/reprint [printer] - restart the last printable job", + }, "\n") +} + +func (b *telegramBot) buildPrintersMessage() string { + records := b.server.printerSettings.list() + if len(records) == 0 { + return "No printers are known yet." + } + lines := []string{"Printers:"} + for _, record := range records { + lines = append(lines, b.formatPrinterSummary(record)) + } + return strings.Join(lines, "\n") +} + +func (b *telegramBot) buildPrinterStatusMessage(target telegramPrinterTarget) string { + name := strings.TrimSpace(target.record.DisplayName) + if name == "" { + name = target.record.PrinterID + } + lines := []string{ + fmt.Sprintf("Printer: %s", name), + fmt.Sprintf("Printer ID: %s", target.record.PrinterID), + } + if target.health == nil || target.health.PrintStatus == nil { + lines = append(lines, "Connected: no") + return strings.Join(lines, "\n") + } + lines = append(lines, "Connected: yes") + status := target.health.PrintStatus + if state := strings.TrimSpace(status.State); state != "" { + lines = append(lines, fmt.Sprintf("State: %s", state)) + } + if fn := strings.TrimSpace(status.Filename); fn != "" { + lines = append(lines, fmt.Sprintf("File: %s", fn)) + } + if layer := formatTelegramLayer(status.CurrentLayer, status.TotalLayer); layer != "" { + lines = append(lines, fmt.Sprintf("Layer: %s", layer)) + } + if progress := status.Progress; progress > 0 { + lines = append(lines, fmt.Sprintf("Progress: %.0f%%", progress*100)) + } + if duration := formatTelegramDuration(status.PrintDuration); duration != "" { + lines = append(lines, fmt.Sprintf("Printed: %s", duration)) + } + if remaining := formatTelegramDuration(status.EstimatedTimeRemaining); remaining != "" { + lines = append(lines, fmt.Sprintf("Remaining: %s", remaining)) + } + if message := strings.TrimSpace(status.Message); message != "" { + lines = append(lines, fmt.Sprintf("Message: %s", message)) + } + return strings.Join(lines, "\n") +} + +func (b *telegramBot) buildPrinterStatusMessageWithLiveData(target telegramPrinterTarget, liveStatus map[string]any) string { + base := b.buildPrinterStatusMessage(target) + if len(liveStatus) == 0 { + return base + } + temperatureLines := temperatureObjectSummary(liveStatus) + fanLines := fanObjectSummary(liveStatus) + if len(temperatureLines) == 0 && len(fanLines) == 0 { + return base + } + lines := []string{base} + if len(temperatureLines) > 0 { + lines = append(lines, "Temperatures:") + lines = append(lines, temperatureLines...) + } + if len(fanLines) > 0 { + lines = append(lines, "Fans:") + lines = append(lines, fanLines...) + } + return strings.Join(lines, "\n") +} + +func (b *telegramBot) formatPrinterSummary(record printerSettingsRecord) string { + name := strings.TrimSpace(record.DisplayName) + if name == "" { + name = record.PrinterID + } + b.server.tunnelsMu.RLock() + t := b.server.tunnels[record.PrinterID] + b.server.tunnelsMu.RUnlock() + if t == nil { + return fmt.Sprintf("- %s (%s): disconnected", name, record.PrinterID) + } + t.healthMu.RLock() + health := t.health + t.healthMu.RUnlock() + state := "connected" + if health != nil && health.PrintStatus != nil && strings.TrimSpace(health.PrintStatus.State) != "" { + state = strings.TrimSpace(health.PrintStatus.State) + } + layer := "" + if health != nil && health.PrintStatus != nil { + layer = formatTelegramLayer(health.PrintStatus.CurrentLayer, health.PrintStatus.TotalLayer) + } + if layer != "" { + return fmt.Sprintf("- %s (%s): %s, layer %s", name, record.PrinterID, state, layer) + } + return fmt.Sprintf("- %s (%s): %s", name, record.PrinterID, state) +} + +func parseTelegramCommand(text string) (string, string) { + text = strings.TrimSpace(text) + if text == "" || !strings.HasPrefix(text, "/") { + return "", "" + } + fields := strings.Fields(text) + if len(fields) == 0 { + return "", "" + } + command := strings.TrimPrefix(fields[0], "/") + if idx := strings.Index(command, "@"); idx >= 0 { + command = command[:idx] + } + command = strings.ToLower(strings.TrimSpace(command)) + args := strings.TrimSpace(strings.TrimPrefix(text, fields[0])) + return command, args +} + +func parseTelegramTemperatureSetArgs(args string) (string, string, float64, error) { + fields := strings.Fields(strings.TrimSpace(args)) + if len(fields) < 2 { + return "", "", 0, fmt.Errorf("usage: /set [printer] ") + } + var printerQuery string + var heater string + var targetText string + switch len(fields) { + case 2: + heater = fields[0] + targetText = fields[1] + default: + printerQuery = strings.Join(fields[:len(fields)-2], " ") + heater = fields[len(fields)-2] + targetText = fields[len(fields)-1] + } + target, err := strconv.ParseFloat(targetText, 64) + if err != nil { + return "", "", 0, fmt.Errorf("temperature must be a number") + } + heaterName, err := normalizeTemperatureHeater(heater) + if err != nil { + return "", "", 0, err + } + return printerQuery, heaterName, target, nil +} + +func normalizeTemperatureHeater(value string) (string, error) { + switch strings.ToLower(strings.TrimSpace(value)) { + case "extruder", "nozzle", "hotend": + return "extruder", nil + case "bed", "heatbed", "heater_bed", "heatedbed": + return "heater_bed", nil + default: + return "", fmt.Errorf("unknown heater %q; use extruder or bed", value) + } +} + +func temperatureHeaterDisplayName(value string) string { + switch strings.ToLower(strings.TrimSpace(value)) { + case "heater_bed": + return "bed" + default: + return strings.TrimSpace(value) + } +} diff --git a/cmd/server/users.go b/cmd/server/users.go new file mode 100644 index 0000000..cf32eb7 --- /dev/null +++ b/cmd/server/users.go @@ -0,0 +1,519 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "golang.org/x/crypto/bcrypt" +) + +type userStore struct { + path string + mu sync.RWMutex + users map[string]userRecord +} + +type userRecord struct { + ID string `json:"id"` + Username string `json:"username"` + PasswordHash string `json:"password_hash"` + Role string `json:"role"` + PrinterGrants []printerGrant `json:"printer_grants,omitempty"` + CreatedAt time.Time `json:"created_at"` +} + +type publicUser struct { + ID string `json:"id"` + Username string `json:"username"` + Role string `json:"role"` + PrinterGrants []printerGrant `json:"printer_grants,omitempty"` + CreatedAt time.Time `json:"created_at"` +} + +type printerGrant struct { + PrinterID string `json:"printer_id"` + Access string `json:"access"` +} + +type userFile struct { + Users []userRecord `json:"users"` +} + +func newUserStore(path string, bootstrapUsername string, bootstrapPassword string) (*userStore, error) { + store := &userStore{ + path: path, + users: make(map[string]userRecord), + } + if err := store.loadOrBootstrap(bootstrapUsername, bootstrapPassword); err != nil { + return nil, err + } + return store, nil +} + +func (s *userStore) loadOrBootstrap(bootstrapUsername string, bootstrapPassword string) error { + s.mu.Lock() + defer s.mu.Unlock() + + if err := s.loadLocked(); err != nil { + return err + } + if len(s.users) > 0 { + return nil + } + if bootstrapUsername == "" || bootstrapPassword == "" { + return errors.New("no users exist and bootstrap credentials are empty") + } + record, err := buildUserRecord(bootstrapUsername, bootstrapPassword, "admin", nil) + if err != nil { + return err + } + s.users[record.ID] = record + return s.saveLocked() +} + +func (s *userStore) loadLocked() error { + if s.path == "" { + return errors.New("users file path is empty") + } + data, err := os.ReadFile(s.path) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + if len(strings.TrimSpace(string(data))) == 0 { + return nil + } + var file userFile + if err := json.Unmarshal(data, &file); err != nil { + return fmt.Errorf("failed to parse users file: %w", err) + } + s.users = make(map[string]userRecord, len(file.Users)) + for _, record := range file.Users { + if record.ID == "" || record.Username == "" || record.PasswordHash == "" || record.Role == "" { + continue + } + record.PrinterGrants = normalizePrinterGrants(record.PrinterGrants) + s.users[record.ID] = record + } + return nil +} + +func (s *userStore) saveLocked() error { + if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil { + return err + } + file := userFile{Users: make([]userRecord, 0, len(s.users))} + for _, record := range s.users { + file.Users = append(file.Users, record) + } + sort.Slice(file.Users, func(i, j int) bool { + if file.Users[i].Role != file.Users[j].Role { + return file.Users[i].Role > file.Users[j].Role + } + return strings.ToLower(file.Users[i].Username) < strings.ToLower(file.Users[j].Username) + }) + encoded, err := json.MarshalIndent(file, "", " ") + if err != nil { + return err + } + encoded = append(encoded, '\n') + return os.WriteFile(s.path, encoded, 0o600) +} + +func (s *userStore) authenticate(username string, password string) (publicUser, bool, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + username = strings.TrimSpace(username) + if username == "" || password == "" { + return publicUser{}, false, nil + } + for _, record := range s.users { + if record.Username != username { + continue + } + if err := bcrypt.CompareHashAndPassword([]byte(record.PasswordHash), []byte(password)); err != nil { + return publicUser{}, false, nil + } + return publicUser{ + ID: record.ID, + Username: record.Username, + Role: record.Role, + PrinterGrants: append([]printerGrant(nil), record.PrinterGrants...), + CreatedAt: record.CreatedAt, + }, true, nil + } + return publicUser{}, false, nil +} + +func (s *userStore) listPublic() []publicUser { + s.mu.RLock() + defer s.mu.RUnlock() + + users := make([]publicUser, 0, len(s.users)) + for _, record := range s.users { + users = append(users, publicUser{ + ID: record.ID, + Username: record.Username, + Role: record.Role, + PrinterGrants: append([]printerGrant(nil), record.PrinterGrants...), + CreatedAt: record.CreatedAt, + }) + } + sort.Slice(users, func(i, j int) bool { + if users[i].Role != users[j].Role { + return users[i].Role > users[j].Role + } + return strings.ToLower(users[i].Username) < strings.ToLower(users[j].Username) + }) + return users +} + +func (s *userStore) getByID(id string) (publicUser, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + + record, ok := s.users[id] + if !ok { + return publicUser{}, false + } + return publicUser{ + ID: record.ID, + Username: record.Username, + Role: record.Role, + PrinterGrants: append([]printerGrant(nil), record.PrinterGrants...), + CreatedAt: record.CreatedAt, + }, true +} + +func (s *userStore) create(username string, password string, role string, grants []printerGrant) (publicUser, error) { + normalizedGrants, err := normalizePrinterGrantsStrict(grants) + if err != nil { + return publicUser{}, err + } + record, err := buildUserRecord(username, password, role, normalizedGrants) + if err != nil { + return publicUser{}, err + } + + s.mu.Lock() + defer s.mu.Unlock() + + for _, existing := range s.users { + if existing.Username == record.Username { + return publicUser{}, fmt.Errorf("username %q already exists", record.Username) + } + } + s.users[record.ID] = record + if err := s.saveLocked(); err != nil { + delete(s.users, record.ID) + return publicUser{}, err + } + return publicUser{ + ID: record.ID, + Username: record.Username, + Role: record.Role, + PrinterGrants: append([]printerGrant(nil), record.PrinterGrants...), + CreatedAt: record.CreatedAt, + }, nil +} + +func (s *userStore) update(id string, password string, role string, grants []printerGrant) (publicUser, error) { + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.users[id] + if !ok { + return publicUser{}, fmt.Errorf("user %q not found", id) + } + original := record + + if password != "" { + hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return publicUser{}, err + } + record.PasswordHash = string(hashed) + } + if role != "" { + role = normalizeRole(role) + if role == "" { + return publicUser{}, fmt.Errorf("invalid role %q", role) + } + if original.Role == "admin" && role != "admin" && s.adminCountLocked() <= 1 { + return publicUser{}, errors.New("cannot demote the last admin") + } + record.Role = role + } + if grants != nil { + normalizedGrants, err := normalizePrinterGrantsStrict(grants) + if err != nil { + return publicUser{}, err + } + record.PrinterGrants = normalizedGrants + } + + s.users[id] = record + if err := s.saveLocked(); err != nil { + s.users[id] = original + return publicUser{}, err + } + return publicUser{ + ID: record.ID, + Username: record.Username, + Role: record.Role, + PrinterGrants: append([]printerGrant(nil), record.PrinterGrants...), + CreatedAt: record.CreatedAt, + }, nil +} + +func (s *userStore) changePassword(userID string, currentPassword string, newPassword string) error { + if len(newPassword) < 4 { + return errors.New("password must be at least 4 characters") + } + + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.users[userID] + if !ok { + return fmt.Errorf("user %q not found", userID) + } + if err := bcrypt.CompareHashAndPassword([]byte(record.PasswordHash), []byte(currentPassword)); err != nil { + return errors.New("current password is incorrect") + } + hashed, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost) + if err != nil { + return err + } + original := record + record.PasswordHash = string(hashed) + s.users[userID] = record + if err := s.saveLocked(); err != nil { + s.users[userID] = original + return err + } + return nil +} + +func (s *userStore) delete(id string, actorID string) error { + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.users[id] + if !ok { + return fmt.Errorf("user %q not found", id) + } + if id == actorID { + return errors.New("cannot delete the currently signed-in user") + } + if record.Role == "admin" && s.adminCountLocked() <= 1 { + return errors.New("cannot delete the last admin") + } + delete(s.users, id) + if err := s.saveLocked(); err != nil { + s.users[id] = record + return err + } + return nil +} + +func (s *userStore) adminCountLocked() int { + count := 0 + for _, record := range s.users { + if record.Role == "admin" { + count++ + } + } + return count +} + +func buildUserRecord(username string, password string, role string, grants []printerGrant) (userRecord, error) { + username = strings.TrimSpace(username) + if len(username) < 3 { + return userRecord{}, errors.New("username must be at least 3 characters") + } + if len(password) < 4 { + return userRecord{}, errors.New("password must be at least 4 characters") + } + role = normalizeRole(role) + if role == "" { + return userRecord{}, fmt.Errorf("invalid role %q", role) + } + hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return userRecord{}, err + } + id, err := newID() + if err != nil { + return userRecord{}, err + } + return userRecord{ + ID: id, + Username: username, + PasswordHash: string(hashed), + Role: role, + PrinterGrants: normalizePrinterGrants(grants), + CreatedAt: time.Now().UTC(), + }, nil +} + +func normalizePrinterGrants(grants []printerGrant) []printerGrant { + if len(grants) == 0 { + return nil + } + seen := make(map[string]printerGrant) + for _, grant := range grants { + printerID := strings.TrimSpace(grant.PrinterID) + access := strings.ToLower(strings.TrimSpace(grant.Access)) + if printerID == "" { + continue + } + switch access { + case "", "read", "viewer": + access = "read" + case "control", "operator", "write": + access = "control" + default: + continue + } + seen[printerID] = printerGrant{PrinterID: printerID, Access: access} + } + if len(seen) == 0 { + return nil + } + normalized := make([]printerGrant, 0, len(seen)) + for _, grant := range seen { + normalized = append(normalized, grant) + } + sort.Slice(normalized, func(i, j int) bool { + return strings.ToLower(normalized[i].PrinterID) < strings.ToLower(normalized[j].PrinterID) + }) + return normalized +} + +func normalizePrinterGrantsStrict(grants []printerGrant) ([]printerGrant, error) { + if len(grants) == 0 { + return nil, nil + } + seen := make(map[string]printerGrant) + for _, grant := range grants { + printerID := strings.TrimSpace(grant.PrinterID) + access := strings.ToLower(strings.TrimSpace(grant.Access)) + if printerID == "" { + return nil, errors.New("printer grant requires a printer id") + } + switch access { + case "read", "control": + default: + return nil, fmt.Errorf("invalid printer access %q for %s", grant.Access, printerID) + } + seen[printerID] = printerGrant{PrinterID: printerID, Access: access} + } + normalized := make([]printerGrant, 0, len(seen)) + for _, grant := range seen { + normalized = append(normalized, grant) + } + sort.Slice(normalized, func(i, j int) bool { + return strings.ToLower(normalized[i].PrinterID) < strings.ToLower(normalized[j].PrinterID) + }) + return normalized, nil +} + +func normalizeRole(role string) string { + switch strings.ToLower(strings.TrimSpace(role)) { + case "", "user": + return "user" + case "admin": + return "admin" + default: + return "" + } +} + +func (s *userStore) canAccessPrinter(userID string, printerID string, control bool) bool { + s.mu.RLock() + defer s.mu.RUnlock() + + record, ok := s.users[userID] + if !ok { + return false + } + if record.Role == "admin" { + return true + } + required := "read" + if control { + required = "control" + } + for _, grant := range record.PrinterGrants { + if grant.PrinterID != printerID { + continue + } + if grant.Access == "control" { + return true + } + if grant.Access == required { + return true + } + } + return false +} + +func (s *userStore) printerAccessLevel(userID string, printerID string) string { + s.mu.RLock() + defer s.mu.RUnlock() + + record, ok := s.users[userID] + if !ok { + return "none" + } + if record.Role == "admin" { + return "admin" + } + level := "none" + for _, grant := range record.PrinterGrants { + if grant.PrinterID != printerID { + continue + } + switch grant.Access { + case "control": + return "control" + case "read": + level = "read" + } + } + return level +} + +func (s *userStore) visiblePrinters(userID string, all []string) []string { + s.mu.RLock() + defer s.mu.RUnlock() + + record, ok := s.users[userID] + if !ok { + return nil + } + if record.Role == "admin" { + return append([]string(nil), all...) + } + allowed := make([]string, 0, len(all)) + for _, printerID := range all { + for _, grant := range record.PrinterGrants { + if grant.PrinterID == printerID { + allowed = append(allowed, printerID) + break + } + } + } + return allowed +} diff --git a/cmd/server/users_test.go b/cmd/server/users_test.go new file mode 100644 index 0000000..0ccbd0f --- /dev/null +++ b/cmd/server/users_test.go @@ -0,0 +1,142 @@ +package main + +import ( + "path/filepath" + "testing" +) + +func TestUserStoreBootstrapAndAuthenticate(t *testing.T) { + store, err := newUserStore(filepath.Join(t.TempDir(), "users.json"), "admin", "admin1234") + if err != nil { + t.Fatal(err) + } + users := store.listPublic() + if len(users) != 1 { + t.Fatalf("users = %d, want 1", len(users)) + } + if users[0].Username != "admin" || users[0].Role != "admin" { + t.Fatalf("bootstrap user = %+v", users[0]) + } + user, ok, err := store.authenticate("admin", "admin1234") + if err != nil { + t.Fatal(err) + } + if !ok || user.Username != "admin" { + t.Fatalf("auth failed: ok=%t user=%+v", ok, user) + } +} + +func TestUserStoreCreateUpdateDelete(t *testing.T) { + store, err := newUserStore(filepath.Join(t.TempDir(), "users.json"), "admin", "admin1234") + if err != nil { + t.Fatal(err) + } + user, err := store.create("alice", "password1", "user", []printerGrant{{PrinterID: "real-printer", Access: "read"}}) + if err != nil { + t.Fatal(err) + } + if user.Username != "alice" || user.Role != "user" { + t.Fatalf("created user = %+v", user) + } + updated, err := store.update(user.ID, "password2", "admin", []printerGrant{{PrinterID: "real-printer", Access: "control"}}) + if err != nil { + t.Fatal(err) + } + if updated.Role != "admin" { + t.Fatalf("updated role = %q, want admin", updated.Role) + } + if len(updated.PrinterGrants) != 1 || updated.PrinterGrants[0].Access != "control" { + t.Fatalf("updated grants = %+v", updated.PrinterGrants) + } + if _, ok, err := store.authenticate("alice", "password2"); err != nil || !ok { + t.Fatalf("password update failed: ok=%t err=%v", ok, err) + } + if err := store.delete(user.ID, "admin-user"); err != nil { + t.Fatal(err) + } + if _, ok := store.getByID(user.ID); ok { + t.Fatal("expected user to be deleted") + } +} + +func TestUserStoreLastAdminProtection(t *testing.T) { + store, err := newUserStore(filepath.Join(t.TempDir(), "users.json"), "admin", "admin1234") + if err != nil { + t.Fatal(err) + } + if err := store.delete(store.listPublic()[0].ID, "someone-else"); err == nil { + t.Fatal("expected last admin deletion to be blocked") + } + if _, err := store.update(store.listPublic()[0].ID, "", "user", nil); err == nil { + t.Fatal("expected last admin demotion to be blocked") + } +} + +func TestCanAccessPrinter(t *testing.T) { + store, err := newUserStore(filepath.Join(t.TempDir(), "users.json"), "admin", "admin1234") + if err != nil { + t.Fatal(err) + } + user, err := store.create("bob", "password1", "user", []printerGrant{{PrinterID: "real-printer", Access: "read"}}) + if err != nil { + t.Fatal(err) + } + if !store.canAccessPrinter(user.ID, "real-printer", false) { + t.Fatal("expected read access") + } + if store.canAccessPrinter(user.ID, "real-printer", true) { + t.Fatal("read-only grant should not allow control") + } + var adminID string + for _, item := range store.listPublic() { + if item.Role == "admin" { + adminID = item.ID + break + } + } + if adminID == "" { + t.Fatal("missing admin user") + } + if !store.canAccessPrinter(adminID, "any-printer", true) { + t.Fatal("admin should access all printers") + } +} + +func TestNormalizePrinterGrantsStrict(t *testing.T) { + grants, err := normalizePrinterGrantsStrict([]printerGrant{ + {PrinterID: "real-printer", Access: "read"}, + {PrinterID: "spare-printer", Access: "control"}, + }) + if err != nil { + t.Fatal(err) + } + if len(grants) != 2 { + t.Fatalf("grants = %+v", grants) + } + if _, err := normalizePrinterGrantsStrict([]printerGrant{{PrinterID: "real-printer", Access: "execute"}}); err == nil { + t.Fatal("expected invalid access to fail") + } +} + +func TestChangePassword(t *testing.T) { + store, err := newUserStore(filepath.Join(t.TempDir(), "users.json"), "admin", "admin1234") + if err != nil { + t.Fatal(err) + } + user, err := store.create("alice", "password1", "user", []printerGrant{{PrinterID: "real-printer", Access: "read"}}) + if err != nil { + t.Fatal(err) + } + if err := store.changePassword(user.ID, "password1", "password2"); err != nil { + t.Fatal(err) + } + if _, ok, err := store.authenticate("alice", "password1"); err != nil || ok { + t.Fatalf("old password should fail: ok=%t err=%v", ok, err) + } + if _, ok, err := store.authenticate("alice", "password2"); err != nil || !ok { + t.Fatalf("new password should work: ok=%t err=%v", ok, err) + } + if err := store.changePassword(user.ID, "wrong", "password3"); err == nil { + t.Fatal("expected current password check to fail") + } +} diff --git a/configs/agent.example.json b/configs/agent.example.json new file mode 100644 index 0000000..426b1be --- /dev/null +++ b/configs/agent.example.json @@ -0,0 +1,15 @@ +{ + "server_url": "ws://127.0.0.1:8080/agent/tunnel", + "printer_id": "test", + "token": "dev-token", + "moonraker_url": "http://127.0.0.1:7125", + "ui_url": "http://mock-moonraker:7125", + "ui_auto_detect": true, + "cameras": [ + { + "name": "default", + "snapshot_url": "http://mock-moonraker:7125/webcam/?action=snapshot", + "stream_url": "http://mock-moonraker:7125/webcam/?action=stream" + } + ] +} diff --git a/configs/agent.real-printer.json b/configs/agent.real-printer.json new file mode 100644 index 0000000..3932100 --- /dev/null +++ b/configs/agent.real-printer.json @@ -0,0 +1,8 @@ +{ + "server_url": "ws://host.docker.internal:8080/agent/tunnel", + "printer_id": "real-printer", + "token": "dev-token", + "moonraker_url": "http://192.168.1.60:7125", + "ui_url": "http://192.168.1.60", + "ui_auto_detect": true +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..9220613 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,45 @@ +services: + mock-moonraker: + build: + context: . + dockerfile: Dockerfile.dev + args: + KA_VERSION: ${KA_VERSION:-dev} + working_dir: /workspace + command: klipperanywhere-mock-moonraker -listen :7125 + ports: + - "7125:7125" + + server: + build: + context: . + dockerfile: Dockerfile.dev + args: + KA_VERSION: ${KA_VERSION:-dev} + working_dir: /workspace + command: klipperanywhere-server -listen :8080 + environment: + KA_AGENT_TOKEN: dev-token + KA_ADMIN_USER: admin + KA_ADMIN_PASSWORD: admin + KA_USERS_FILE: /workspace/data/users.json + ports: + - "8080:8080" + volumes: + - ./data:/workspace/data + + agent: + build: + context: . + dockerfile: Dockerfile.dev + args: + KA_VERSION: ${KA_VERSION:-dev} + working_dir: /workspace + command: > + klipperanywhere-agent + -config configs/agent.example.json + -server ws://server:8080/agent/tunnel + -moonraker http://mock-moonraker:7125 + depends_on: + - server + - mock-moonraker diff --git a/docs/agent-config.md b/docs/agent-config.md new file mode 100644 index 0000000..ae7d32f --- /dev/null +++ b/docs/agent-config.md @@ -0,0 +1,115 @@ +# Agent Config + +The agent can be configured with a JSON file and optional CLI overrides. + +The agent also writes a small local status file by default at +`/var/lib/klipperanywhere/agent-state.json`. You can change that with +`state_file` in the JSON config or `-state-file` on the command line if the host +needs a different persistent path. + +## Example + +```json +{ + "server_url": "wss://remote.example.com/agent/tunnel", + "printer_id": "ender3-v3-ke", + "token": "replace-with-agent-token", + "moonraker_url": "http://127.0.0.1:7125", + "ui_url": "http://127.0.0.1", + "ui_auto_detect": true, + "cameras": [ + { + "name": "default", + "snapshot_url": "http://127.0.0.1:8080/?action=snapshot", + "stream_url": "http://127.0.0.1:8080/?action=stream" + } + ] +} +``` + +## Run With A Config File + +```sh +klipperanywhere-agent -config /etc/klipperanywhere/agent.json +``` + +## CLI Overrides + +The CLI flags override values from the config file: + +```sh +klipperanywhere-agent \ + -config /etc/klipperanywhere/agent.json \ + -server wss://remote.example.com/agent/tunnel \ + -printer-id ender3-v3-ke +``` + +## Suggested Printer Path + +On a full Linux host: + +```text +/etc/klipperanywhere/agent.json +``` + +On constrained rooted printer firmware, use whichever persistent path survives +firmware restarts and updates. The exact path should be confirmed per printer model. + +## Cameras + +The agent automatically checks Moonraker's webcam API: + +```text +GET /server/webcams/list +``` + +Moonraker returns webcam entries with `stream_url` and `snapshot_url` fields. The +agent resolves relative URLs against the configured `moonraker_url`. + +Manual camera entries remain supported. If a manual camera has the same name as a +Moonraker-discovered camera, the manual config overrides the discovered URLs. + +Camera URLs are always resolved by the agent, not by the server. This keeps the +server from requesting arbitrary LAN resources through the printer network. + +Each camera needs a stable `name`. Snapshot and stream support are independent: + +- `snapshot_url`: a single image response. +- `stream_url`: an MJPEG-style `multipart/x-mixed-replace` response. + +Common webcam stacks expose paths similar to: + +```text +http://127.0.0.1/webcam/?action=snapshot +http://127.0.0.1/webcam/?action=stream +``` + +The authenticated server routes are: + +```text +/p/{printer_id}/camera/{camera_name}/snapshot +/p/{printer_id}/camera/{camera_name}/stream +``` + +## Printer UI + +The agent can proxy a local Mainsail or Fluidd instance through the authenticated +server route: + +```text +/printers/{printer_id}/ui/ +``` + +Set `ui_url` when the UI origin is known. If `ui_url` is empty and +`ui_auto_detect` is enabled, the agent tries these local origins in order: + +```text +http://127.0.0.1 +http://127.0.0.1:80 +http://127.0.0.1:4408 +http://127.0.0.1:8080 +``` + +The agent reports `ui_url`, `ui_reachable`, and `ui_source` in heartbeat data so +the dashboard can show whether the printer UI was configured explicitly or found +automatically. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..f62630c --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,121 @@ +# Architecture + +## Problem + +Klipper printers are usually controlled through Moonraker, Mainsail, Fluidd, and one +or more local camera streams. These services are normally safe on a trusted LAN, but +they should not be exposed directly to the internet. + +KlipperAnywhere provides a self-hosted remote access layer where the printer-side +agent dials out to a server the user controls. Remote clients connect to that server, +and the server brokers access back to the printer through the agent connection. + +## High-Level Design + +```text +Browser / mobile app + | + | HTTPS + v +KlipperAnywhere server + | + | outbound tunnel from printer network + v +KlipperAnywhere agent + | + | LAN HTTP/WebSocket + v +Moonraker, Mainsail, Fluidd, webcam services +``` + +## Server Responsibilities + +- Terminate HTTPS. +- Authenticate users. +- Register printers and issue agent credentials. +- Accept outbound agent tunnel connections. +- Authorize requests to printers. +- Proxy HTTP and WebSocket traffic to Moonraker/UI services. +- Relay webcam streams or snapshots. +- Store audit events. + +## Agent Responsibilities + +- Run on the printer host or another device on the same LAN. +- Connect outbound to the server and keep the tunnel alive. +- Verify server identity. +- Discover or configure local Moonraker, UI, and camera endpoints. +- Forward allowed traffic between the server and local services. +- Report printer health, tunnel health, and local endpoint availability. + +## MVP Protocol + +The simplest reliable MVP is a persistent WebSocket tunnel: + +- Agent opens `wss://server.example.com/agent/tunnel`. +- Agent authenticates using a one-time enrollment token, then receives a long-lived + printer credential. +- Server multiplexes proxied HTTP/WebSocket requests over the tunnel. +- Agent performs local requests to Moonraker or webcam endpoints and streams responses + back to the server. + +This is easier to deploy than WireGuard/Tailscale-style networking and keeps the +initial surface area small. A later version can add native QUIC/WebTransport or +WireGuard for better performance. + +## Data Model + +- `User`: login identity and server-wide permissions, persisted in a local JSON + file for the MVP. +- `Printer`: display name, owner, status, and registered agent identity. +- `AgentCredential`: revocable secret or certificate used by the agent. +- `AccessGrant`: maps users or API tokens to printers and permission scopes. +- `AuditEvent`: append-only JSONL records for logins, account changes, printer + UI opens, and control actions. + +## Permission Scopes + +- `printer:read`: view status, temperatures, job progress, and files. +- `printer:control`: pause, resume, cancel, home, move axes, and run macros. +- `printer:upload`: upload G-code. +- `printer:admin`: edit printer connection settings and agent credentials. +- `camera:view`: view snapshots or streams. + +## Deployment Shape + +For MVP: + +- `server` container +- local users file for account persistence +- optional `redis` container for transient tunnel/session state +- `agent` installed as a service or init script on the printer host + +On rooted printer appliances, such as Creality/Nebula-style Klipper devices, the +agent should not assume a full Debian userspace. It should be installable as a +single Go binary with `CGO_ENABLED=0`, and startup should support `systemd`, +OpenRC, SysV init, BusyBox init scripts, or a documented manual launch path. + +For early development, SQLite is acceptable, but Postgres should be the production +target because multi-printer deployments and audit logs benefit from stronger +operational behavior. + +## Key Risks + +- Remote control of printers is physically risky. Authorization and audit logs are + not optional. +- Moonraker APIs include powerful endpoints. The proxy should enforce scope checks + before forwarding dangerous calls. +- Camera streaming can dominate bandwidth. Snapshot polling should be available as a + low-bandwidth fallback. +- A compromised server can control connected printers. Agent-side allowlists and + read-only modes reduce blast radius. + +## Suggested First Milestone + +Build a minimal vertical slice: + +1. Server exposes HTTPS routes for one printer. +2. Agent connects to server over WebSocket. +3. Browser can access Moonraker `/printer/info` through the server. +4. Server logs every proxied request with user, printer, method, and path. +5. Browser can open a proxied WebSocket to Moonraker. diff --git a/docs/auth.md b/docs/auth.md new file mode 100644 index 0000000..fad1b31 --- /dev/null +++ b/docs/auth.md @@ -0,0 +1,88 @@ +# Authentication + +The current server has a starter authentication layer: + +- persistent local users in a JSON file +- form login at `/login` +- logout at `/logout` +- HTTP-only session cookie +- protected dashboard, API, and printer proxy routes +- self-service account page at `/account` +- admin audit trail at `/audit` +- admin-only user management at `/users` +- per-user printer grants with read or control access + +For local development, Docker Compose uses: + +```text +username: admin +password: admin +``` + +Run the server with different credentials: + +```powershell +$env:KA_AGENT_TOKEN = "replace-agent-token" +$env:KA_ADMIN_USER = "your-user" +$env:KA_ADMIN_PASSWORD = "your-password" +klipperanywhere-server -listen :8080 +``` + +When serving over HTTPS, enable secure cookies: + +```powershell +$env:KA_COOKIE_SECURE = "true" +klipperanywhere-server -listen :8080 +``` + +CLI flags still exist for local overrides, but environment variables are preferred +for secrets. + +The users file defaults to `data/users.json` in the server working directory. +Set `KA_USERS_FILE` if you want it stored elsewhere. + +## Current Protections + +- `/login` is rate limited by client IP. +- Session cookies are HTTP-only and expire after 12 hours. +- `/logout` requires POST plus a per-session CSRF token. +- `/dashboard`, `/users`, `/api/users*`, `/api/printers*`, + `/account`, `/audit`, `/printers/{printer_id}/ui/*`, and `/p/*` require a session. +- printer routes also enforce per-user grants, so users only see printers they + have been assigned. +- `/api/account` lets the signed-in user change their own password after + confirming the current password. +- `/api/audit` returns recent audit events for admins. +- Moonraker browser proxy traffic defaults to read-only mode. Set + `KA_CONTROL_MODE=full` or `-control-mode full` only when authenticated users + should be allowed to send normal Mainsail/Fluidd control commands. +- The server warns when default credentials, default agent token, or insecure + cookies are used. + +## Printer Control Mode + +The server supports two control modes: + +```text +readonly +full +``` + +`readonly` is the default. It allows health, info, camera, UI asset, and common +Moonraker read paths, but blocks representative risky HTTP and WebSocket control +traffic such as G-code scripts, print pause/resume/cancel, emergency stop, machine +commands, and file mutation routes. + +`full` forwards authenticated browser traffic to Moonraker without that starter +policy block. Use it only behind HTTPS with non-default credentials. + +## Public Exposure Notes + +This is still a lightweight self-hosted auth layer. Before recommending public +internet deployment, the project still needs: + +- durable session storage and explicit session secret configuration +- CSRF protection for all state-changing browser requests +- rate limiting on login +- TLS deployment guide +- audit logging tied to user identity diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..4c6e0d9 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,110 @@ +# Development + +## Local Tunnel Smoke Test + +This first vertical slice proxies Moonraker HTTP requests. Moonraker WebSocket +proxying is the next protocol increment. + +If Docker is available, run the whole smoke-test stack with: + +```powershell +$env:KA_VERSION = .\scripts\version.ps1 +docker compose up --build +``` + +The development image copies the repo into the container and builds the binaries. +Re-run with `--build` after source changes. + +If you want the containers to carry a git-derived build version, keep `KA_VERSION` +set before rebuilding. Otherwise the build falls back to `dev`. + +Then request Moonraker through the server: + +```powershell +Invoke-RestMethod http://127.0.0.1:8080/p/test/moonraker/printer/info +``` + +If Go is installed locally, run the three processes manually. + +Run the three processes in separate terminals: + +```powershell +go run ./cmd/mock-moonraker -listen :7125 +``` + +```powershell +go run ./cmd/server -listen :8080 -agent-token dev-token +``` + +```powershell +go run ./cmd/agent -config configs/agent.example.json +``` + +Then request Moonraker through the server: + +```powershell +Invoke-RestMethod http://127.0.0.1:8080/p/test/moonraker/printer/info +``` + +The response should come from the mock Moonraker process through the outbound agent +tunnel. + +Check the latest heartbeat received by the server: + +```powershell +Invoke-RestMethod http://127.0.0.1:8080/api/printers/test/health +``` + +The response includes whether the agent is connected and whether Moonraker was +reachable during the agent's last heartbeat. + +Fetch combined printer detail data: + +```powershell +Invoke-RestMethod http://127.0.0.1:8080/api/printers/test +``` + +The response combines connection health, heartbeat data, and Moonraker +`/printer/info` output for the printer detail page. + +The Docker smoke-test config also exposes a mock camera: + +```powershell +Invoke-WebRequest http://127.0.0.1:8080/p/test/camera/default/snapshot +``` + +The stream endpoint is long-lived: + +```powershell +curl.exe --cookie "ka_session=" http://127.0.0.1:8080/p/test/camera/default/stream +``` + +## Live Printer Smoke Test + +When a real printer agent is connected to the server, run the live smoke test +against the published server port: + +```powershell +make test-live-printer +``` + +That check logs in, verifies the live printer heartbeat, confirms +`/p/{printer_id}/moonraker/printer/info`, and optionally exercises the proxied UI +when the live agent reports one. + +## Cross-Compile Agent + +For a rooted printer, first check the target architecture over SSH: + +```sh +uname -m +cat /proc/cpuinfo +``` + +Common builds: + +```powershell +$env:CGO_ENABLED = "0"; $env:GOOS = "linux"; $env:GOARCH = "arm64"; go build -o dist/klipperanywhere-agent-linux-arm64 ./cmd/agent +$env:CGO_ENABLED = "0"; $env:GOOS = "linux"; $env:GOARCH = "arm"; $env:GOARM = "7"; go build -o dist/klipperanywhere-agent-linux-armv7 ./cmd/agent +$env:CGO_ENABLED = "0"; $env:GOOS = "linux"; $env:GOARCH = "mipsle"; go build -o dist/klipperanywhere-agent-linux-mipsle ./cmd/agent +``` diff --git a/docs/ender-3-v3-ke.md b/docs/ender-3-v3-ke.md new file mode 100644 index 0000000..cf2dd24 --- /dev/null +++ b/docs/ender-3-v3-ke.md @@ -0,0 +1,55 @@ +# Ender 3 V3 KE Notes + +The Ender 3 V3 KE can be tested like a constrained rooted Klipper appliance. Do not +install a startup hook until the agent works manually. + +## Identify Architecture + +SSH into the printer and run: + +```sh +uname -m +cat /proc/cpuinfo +``` + +Common mappings: + +```text +aarch64 -> linux-arm64 +armv7l -> linux-armv7 +x86_64 -> linux-amd64 +``` + +## Manual Run + +Copy the matching binary and `agent.json` to a persistent location on the printer. +The exact persistent path can vary by firmware/root method. + +Example: + +```sh +chmod +x ./klipperanywhere-agent +./klipperanywhere-agent -config ./agent.json +``` + +Use: + +```text +moonraker_url: http://127.0.0.1:7125 +``` + +The agent should discover Moonraker webcams from: + +```text +GET /server/webcams/list +``` + +If Moonraker resolves webcam URLs to `127.0.0.1`, that is correct when the agent is +running on the printer itself. + +## After Manual Success + +Only after the dashboard shows the printer and camera should you add startup +integration. Use `scripts/install-agent.sh` and let it pick the right host runtime. +If the printer firmware does not expose a standard service manager, keep the same +command that worked manually and wire it into the local init hook. diff --git a/docs/install-agent.md b/docs/install-agent.md new file mode 100644 index 0000000..a152ac9 --- /dev/null +++ b/docs/install-agent.md @@ -0,0 +1,140 @@ +# Install Agent + +## Build + +On Windows: + +```powershell +.\scripts\build-agent.ps1 +``` + +On Linux or macOS: + +```sh +make build-agent +``` + +Pass a version explicitly if you are cutting a release build: + +```powershell +.\scripts\build-agent.ps1 -Version (.\scripts\version.ps1) +``` + +The binaries are written to `dist/`: + +```text +klipperanywhere-agent-linux-amd64 +klipperanywhere-agent-linux-arm64 +klipperanywhere-agent-linux-armv7 +klipperanywhere-agent-linux-mipsle +``` + +## Manual Test First + +Copy the matching binary and config to the printer host, then run it manually: + +```sh +chmod +x ./klipperanywhere-agent +./klipperanywhere-agent -config ./agent.json +``` + +Check the server dashboard before installing it as a service. + +## Install + +The installer auto-detects the host runtime and installs the agent as: + +- a `systemd` service when `systemctl` and a systemd userspace are present +- an OpenRC service when `rc-update` is available +- a SysV-style init script when `update-rc.d` or `chkconfig` is available +- a BusyBox-style boot hook when only lightweight init directories exist + +Run it from the repo root: + +```sh +sudo sh ./scripts/install-agent.sh ./dist/klipperanywhere-agent-linux-arm64 ./agent.json +``` + +Check logs on `systemd` hosts: + +```sh +journalctl -u klipperanywhere-agent -f +``` + +Check local printer-host status: + +```sh +/usr/local/bin/klipperanywhere-agent status -config /etc/klipperanywhere/agent.json +``` + +Add `-json` if you want machine-readable output. + +Print the embedded build version: + +```sh +/usr/local/bin/klipperanywhere-agent version +``` + +## Bootstrap From A Release + +If you already have the config file on the printer host, the bootstrapper will +download the correct binary for the host architecture and install it in one step. +It expects to sit alongside the installer scripts from this repo or a release +bundle that includes them: + +```sh +sudo sh ./scripts/bootstrap-agent.sh --config /etc/klipperanywhere/agent.json +``` + +You can override the release asset base URL when testing locally: + +```sh +sudo sh ./scripts/bootstrap-agent.sh \ + --config /etc/klipperanywhere/agent.json \ + --release-base-url https://github.com/klipperanywhere/klipperanywhere/releases/latest/download +``` + +## Install Over SSH + +If you are logged into the server web UI as an admin, you can install a printer +agent over SSH from the new `/install` page. Enter the printer IP, SSH user, +password, and a printer-reachable server URL, then KlipperAnywhere will: + +- detect the printer architecture over SSH +- download the matching agent binary on the server +- upload the binary, config, and init files to the printer +- run the standard installer remotely +- wait for the agent to call back and appear in `/api/printers` + +If you open `/install` from a printer detail page, the printer ID will prefill. + +The SSH account should be `root` or a user with passwordless sudo. + +Use the `Printer host type` selector on `/install` if the printer is running +Rinkhals. In that mode the installer uploads a Rinkhals app bundle instead of +installing a host service. The app bundle lives under +`/useremain/home/rinkhals/apps/60-klipperanywhere-agent` and includes: + +- `app.json` +- `app.sh` +- `klipperanywhere-agent` +- `agent.json` + +The app script starts the agent inside the Rinkhals runtime and uses the same +SSH-installed config fields as the standard service path. + +On BusyBox or SysV-style hosts, the installer places `/etc/init.d/klipperanywhere-agent` +in place and starts it using the best available boot registration it can find. If the +host does not expose a runtime manager, start it manually with: + +```sh +/etc/init.d/klipperanywhere-agent start +``` + +Uninstall: + +```sh +sudo sh ./scripts/uninstall-agent.sh +``` + +The uninstall script leaves `/etc/klipperanywhere/agent.json` in place. diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..7b61a6c --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,53 @@ +# Roadmap + +## Phase 0: Repo Foundation + +- Pick implementation stack. +- Add server, agent, and web package layout. +- Add Docker Compose for local development. +- Add basic CI for linting and tests. + +## Phase 1: Moonraker Remote Access + +- Agent enrollment. +- Persistent agent tunnel. +- HTTP proxy to Moonraker. +- WebSocket proxy to Moonraker. +- User auth and printer ownership. +- Audit log for proxied requests. + +## Phase 2: Printer UI Access + +- Proxy Mainsail and Fluidd. +- Support path rewriting and asset caching. +- Add per-printer access URLs. +- Add read-only mode. + +## Phase 3: Cameras + +- Snapshot relay. +- MJPEG relay. +- Optional WebRTC relay. +- Bandwidth limits and stream timeouts. + +## Phase 4: Notifications + +- Print started, paused, resumed, completed, failed. +- Temperature and filament alerts. +- Webhook provider. +- Email, Discord, Telegram, and PushOver integrations. + +## Phase 5: Advanced Safety + +- Scope-aware Moonraker API filtering. +- Optional second confirmation for risky actions. +- Emergency stop prominence. +- Session expiry and device management. + +## Phase 6: Failure Detection + +- Camera frame sampling pipeline. +- Pluggable detector interface. +- Local detector option for full self-hosting. +- Optional external detector integration for users who want it. + diff --git a/docs/threat-model.md b/docs/threat-model.md new file mode 100644 index 0000000..fa90e49 --- /dev/null +++ b/docs/threat-model.md @@ -0,0 +1,38 @@ +# Threat Model + +## Assets + +- Printer control APIs. +- G-code files. +- Camera feeds. +- User credentials. +- Agent credentials. +- Audit logs. + +## Trust Boundaries + +- Public internet to server. +- Server to printer-side agent. +- Agent to local printer services. +- Browser session to server APIs. + +## Primary Threats + +- Unauthorized remote control of a printer. +- Credential theft from the server or agent host. +- Cross-printer access between users. +- Server-side request forgery through proxy endpoints. +- Abuse of Moonraker endpoints that can run commands or modify files. +- Camera feed exposure. + +## Mitigations + +- Require HTTPS for all browser and agent traffic. +- Use per-printer revocable agent credentials. +- Scope all user access by printer and permission. +- Enforce an allowlist for proxied hosts and ports on the agent. +- Enforce method/path policy for dangerous Moonraker routes. +- Log sensitive actions with user, printer, method, path, IP, and timestamp. +- Support read-only printer sessions. +- Keep camera permissions separate from printer control permissions. + diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..1e0a983 --- /dev/null +++ b/go.mod @@ -0,0 +1,6 @@ +module github.com/klipperanywhere/klipperanywhere + +go 1.22 + +require github.com/gorilla/websocket v1.5.3 +require golang.org/x/crypto v0.23.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b3bdb18 --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= diff --git a/internal/protocol/protocol.go b/internal/protocol/protocol.go new file mode 100644 index 0000000..e4f9d15 --- /dev/null +++ b/internal/protocol/protocol.go @@ -0,0 +1,92 @@ +package protocol + +const ( + MessageHTTPRequest = "http_request" + MessageHTTPResponse = "http_response" + MessageHeartbeat = "heartbeat" + MessageConfigSync = "config_sync" + MessageAgentUpdate = "agent_update" + MessageError = "error" +) + +type Header struct { + Name string `json:"name"` + Values []string `json:"values"` +} + +type Message struct { + ID string `json:"id"` + Type string `json:"type"` + Target string `json:"target,omitempty"` + CameraName string `json:"camera_name,omitempty"` + CameraKind string `json:"camera_kind,omitempty"` + Method string `json:"method,omitempty"` + Path string `json:"path,omitempty"` + Headers []Header `json:"headers,omitempty"` + Body string `json:"body,omitempty"` + WSMessageType int `json:"ws_message_type,omitempty"` + Status int `json:"status,omitempty"` + Error string `json:"error,omitempty"` + End bool `json:"end,omitempty"` + Health *Health `json:"health,omitempty"` + Settings *Settings `json:"settings,omitempty"` + Update *AgentUpdateRequest `json:"update,omitempty"` +} + +type Health struct { + AgentVersion string `json:"agent_version"` + Hostname string `json:"hostname"` + MoonrakerURL string `json:"moonraker_url"` + MoonrakerReachable bool `json:"moonraker_reachable"` + MoonrakerState string `json:"moonraker_state,omitempty"` + MoonrakerMessage string `json:"moonraker_message,omitempty"` + PrintStatus *PrintStatus `json:"print_status,omitempty"` + UIURL string `json:"ui_url,omitempty"` + UIAutoDetect bool `json:"ui_auto_detect"` + UIReachable bool `json:"ui_reachable"` + UISource string `json:"ui_source,omitempty"` + ControlMode string `json:"control_mode,omitempty"` + CheckedAtUnix int64 `json:"checked_at_unix"` + Cameras []CameraHealth `json:"cameras,omitempty"` +} + +type Settings struct { + ControlMode string `json:"control_mode,omitempty"` + UIURL string `json:"ui_url,omitempty"` + UIAutoDetect bool `json:"ui_auto_detect"` +} + +type AgentUpdateRequest struct { + ReleaseURL string `json:"release_url,omitempty"` + Version string `json:"version,omitempty"` +} + +type PrintStatus struct { + State string `json:"state,omitempty"` + Filename string `json:"filename,omitempty"` + Message string `json:"message,omitempty"` + Progress float64 `json:"progress,omitempty"` + PrintDuration float64 `json:"print_duration,omitempty"` + TotalDuration float64 `json:"total_duration,omitempty"` + FilamentUsed float64 `json:"filament_used,omitempty"` + EstimatedTimeRemaining float64 `json:"estimated_time_remaining,omitempty"` + CurrentLayer int `json:"current_layer,omitempty"` + TotalLayer int `json:"total_layer,omitempty"` + MoonrakerStatus map[string]any `json:"moonraker_status,omitempty"` + MoonrakerMetadata map[string]any `json:"moonraker_metadata,omitempty"` + MoonrakerMetadataFilename string `json:"moonraker_metadata_filename,omitempty"` + LayerSource string `json:"layer_source,omitempty"` +} + +type CameraHealth struct { + Name string `json:"name"` + Source string `json:"source,omitempty"` + Service string `json:"service,omitempty"` + Location string `json:"location,omitempty"` + AspectRatio string `json:"aspect_ratio,omitempty"` + Rotation int `json:"rotation,omitempty"` + FlipHorizontal bool `json:"flip_horizontal,omitempty"` + FlipVertical bool `json:"flip_vertical,omitempty"` + HasSnapshot bool `json:"has_snapshot"` + HasStream bool `json:"has_stream"` +} diff --git a/packaging/klipperanywhere-agent.initd b/packaging/klipperanywhere-agent.initd new file mode 100644 index 0000000..7e41a76 --- /dev/null +++ b/packaging/klipperanywhere-agent.initd @@ -0,0 +1,77 @@ +#!/bin/sh + +AGENT_BIN="${AGENT_BIN:-/usr/local/bin/klipperanywhere-agent}" +AGENT_CONFIG="${AGENT_CONFIG:-/etc/klipperanywhere/agent.json}" +AGENT_ARGS="${AGENT_ARGS:--config $AGENT_CONFIG}" +PIDFILE="${PIDFILE:-/run/klipperanywhere-agent.pid}" +LOGFILE="${LOGFILE:-/var/log/klipperanywhere-agent.log}" +NAME="klipperanywhere-agent" + +start_agent() { + if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then + echo "$NAME already running" + return 0 + fi + + mkdir -p "$(dirname "$PIDFILE")" "$(dirname "$LOGFILE")" + + if command -v start-stop-daemon >/dev/null 2>&1; then + start-stop-daemon \ + --start \ + --background \ + --make-pidfile \ + --pidfile "$PIDFILE" \ + --exec "$AGENT_BIN" \ + -- $AGENT_ARGS + return $? + fi + + if command -v setsid >/dev/null 2>&1; then + sh -c "exec \"$AGENT_BIN\" $AGENT_ARGS >>\"$LOGFILE\" 2>&1" & + else + nohup "$AGENT_BIN" $AGENT_ARGS >>"$LOGFILE" 2>&1 & + fi + echo $! > "$PIDFILE" +} + +stop_agent() { + if [ ! -f "$PIDFILE" ]; then + echo "$NAME is not running" + return 0 + fi + + pid="$(cat "$PIDFILE" 2>/dev/null || true)" + if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then + kill "$pid" + for _ in 1 2 3 4 5; do + if ! kill -0 "$pid" 2>/dev/null; then + break + fi + sleep 1 + done + if kill -0 "$pid" 2>/dev/null; then + kill -9 "$pid" 2>/dev/null || true + fi + fi + rm -f "$PIDFILE" +} + +status_agent() { + if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then + echo "$NAME is running" + return 0 + fi + echo "$NAME is stopped" + return 3 +} + +case "${1:-}" in + start) start_agent ;; + stop) stop_agent ;; + restart) stop_agent && start_agent ;; + status) status_agent ;; + *) + echo "usage: $0 {start|stop|restart|status}" >&2 + exit 2 + ;; +esac diff --git a/packaging/klipperanywhere-agent.service b/packaging/klipperanywhere-agent.service new file mode 100644 index 0000000..190db17 --- /dev/null +++ b/packaging/klipperanywhere-agent.service @@ -0,0 +1,15 @@ +[Unit] +Description=KlipperAnywhere Agent +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/klipperanywhere-agent -config /etc/klipperanywhere/agent.json +Restart=always +RestartSec=5 +User=root + +[Install] +WantedBy=multi-user.target + diff --git a/packaging/rinkhals/klipperanywhere-agent/app.json b/packaging/rinkhals/klipperanywhere-agent/app.json new file mode 100644 index 0000000..2b228dc --- /dev/null +++ b/packaging/rinkhals/klipperanywhere-agent/app.json @@ -0,0 +1,6 @@ +{ + "$version": "1", + "name": "klipperanywhere-agent", + "description": "Runs the KlipperAnywhere tunnel agent on a Rinkhals printer host.", + "version": "0.1" +} diff --git a/packaging/rinkhals/klipperanywhere-agent/app.sh b/packaging/rinkhals/klipperanywhere-agent/app.sh new file mode 100644 index 0000000..8a42398 --- /dev/null +++ b/packaging/rinkhals/klipperanywhere-agent/app.sh @@ -0,0 +1,145 @@ +#!/bin/sh +set -e + +TOOLS_SH=/useremain/rinkhals/.current/tools.sh +wait_for_tools() { + tries=30 + while [ "$tries" -gt 0 ]; do + if [ -f "$TOOLS_SH" ]; then + return 0 + fi + tries=$((tries - 1)) + sleep 2 + done + return 1 +} + +if ! wait_for_tools; then + echo "missing Rinkhals tools.sh" >&2 + exit 2 +fi +. "$TOOLS_SH" + +APP_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +APP_LOG="$APP_ROOT/klipperanywhere-agent.log" +APP_PID="$APP_ROOT/klipperanywhere-agent.pid" +APP_LOCK="$APP_ROOT/.start.lock" +AGENT_BIN="$APP_ROOT/klipperanywhere-agent" +AGENT_CFG="$APP_ROOT/agent.json" + +agent_pids() { + PIDS="" + if [ -f "$APP_PID" ]; then + PID=$(cat "$APP_PID" 2>/dev/null || true) + if [ -n "$PID" ]; then + PIDS="$PID" + fi + fi + for proc in /proc/[0-9]*; do + [ -e "$proc/cmdline" ] || continue + pid=${proc#/proc/} + case " $PIDS " in + *" $pid "*) continue ;; + esac + cmd=$(tr '\0' ' ' < "$proc/cmdline" 2>/dev/null || true) + case "$cmd" in + *"$AGENT_BIN"*) + PIDS="$PIDS $pid" + ;; + esac + done + echo "$PIDS" +} + +status() { + PIDS=$(agent_pids) + if [ -n "$PIDS" ]; then + report_status "$APP_STATUS_STARTED" "$PIDS" + return + fi + rm -f "$APP_PID" + report_status "$APP_STATUS_STOPPED" "" +} + +start() { + cd "$APP_ROOT" + if mkdir "$APP_LOCK" 2>/dev/null; then + echo "$$" > "$APP_LOCK/pid" + trap 'rm -rf "$APP_LOCK"' EXIT INT TERM + else + LOCK_PID=$(cat "$APP_LOCK/pid" 2>/dev/null || true) + if [ -n "$LOCK_PID" ] && kill -0 "$LOCK_PID" 2>/dev/null; then + sleep 2 + PIDS=$(agent_pids) + if [ -n "$PIDS" ]; then + exit 0 + fi + echo "another start is already in progress" >&2 + exit 1 + fi + rm -rf "$APP_LOCK" + mkdir "$APP_LOCK" + echo "$$" > "$APP_LOCK/pid" + trap 'rm -rf "$APP_LOCK"' EXIT INT TERM + fi + if [ ! -x "$AGENT_BIN" ]; then + echo "missing agent binary: $AGENT_BIN" >&2 + exit 1 + fi + if [ ! -f "$AGENT_CFG" ]; then + echo "missing agent config: $AGENT_CFG" >&2 + exit 1 + fi + PIDS=$(agent_pids) + if [ -n "$PIDS" ]; then + exit 0 + fi + : > "$APP_LOG" + echo "starting KlipperAnywhere agent" >> "$APP_LOG" + PID=$(sh -c 'cd "$1" && nohup "$2" -config "$3" >> "$4" 2>&1 /dev/null | tail -n1 | tr -d '\r') + if [ -z "$PID" ]; then + echo "failed to launch KlipperAnywhere agent" >&2 + exit 1 + fi + echo "$PID" > "$APP_PID" + sleep 2 + if ! kill -0 "$PID" 2>/dev/null; then + echo "KlipperAnywhere agent exited immediately; see $APP_LOG" >&2 + rm -f "$APP_PID" + exit 1 + fi +} + +stop() { + PIDS=$(agent_pids) + if [ -n "$PIDS" ]; then + for PID in $PIDS; do + kill "$PID" 2>/dev/null || true + done + sleep 2 + REMAINING="" + for PID in $PIDS; do + if kill -0 "$PID" 2>/dev/null; then + REMAINING="$REMAINING $PID" + fi + done + if [ -n "$REMAINING" ]; then + for PID in $REMAINING; do + kill -KILL "$PID" 2>/dev/null || true + done + sleep 1 + fi + fi + rm -f "$APP_PID" + rm -rf "$APP_LOCK" +} + +case "${1:-}" in + status) status ;; + start) start ;; + stop) stop ;; + *) + echo "usage: $0 {status|start|stop}" >&2 + exit 2 + ;; +esac diff --git a/scripts/bootstrap-agent.sh b/scripts/bootstrap-agent.sh new file mode 100644 index 0000000..caad545 --- /dev/null +++ b/scripts/bootstrap-agent.sh @@ -0,0 +1,95 @@ +#!/bin/sh +set -eu + +CONFIG_SRC="${CONFIG_SRC:-}" +RELEASE_BASE_URL="${RELEASE_BASE_URL:-https://github.com/klipperanywhere/klipperanywhere/releases/latest/download}" +ARCH_OVERRIDE="${ARCH_OVERRIDE:-}" + +usage() { + cat >&2 <<'EOF' +usage: bootstrap-agent.sh --config [--release-base-url ] [--arch ] + +Downloads the matching agent binary for this host and installs it using the +unified installer. Supported arches: amd64, arm64, armv7, mipsle. +EOF + exit 2 +} + +while [ $# -gt 0 ]; do + case "$1" in + --config) + shift + CONFIG_SRC="${1:-}" + ;; + --release-base-url) + shift + RELEASE_BASE_URL="${1:-}" + ;; + --arch) + shift + ARCH_OVERRIDE="${1:-}" + ;; + -h|--help) + usage + ;; + *) + echo "unknown argument: $1" >&2 + usage + ;; + esac + shift +done + +if [ -z "$CONFIG_SRC" ]; then + echo "missing --config" >&2 + usage +fi +if [ "$(id -u)" -ne 0 ]; then + echo "run as root" >&2 + exit 1 +fi +if [ ! -f "$CONFIG_SRC" ]; then + echo "missing config file: $CONFIG_SRC" >&2 + exit 1 +fi + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +ARCH="${ARCH_OVERRIDE:-$(detect_arch)}" +ASSET="klipperanywhere-agent-linux-$ARCH" +TMP_DIR="$(mktemp -d)" +trap 'rm -rf "$TMP_DIR"' EXIT INT TERM + +download "$RELEASE_BASE_URL/$ASSET" "$TMP_DIR/$ASSET" +chmod 0755 "$TMP_DIR/$ASSET" + +exec sh "$SCRIPT_DIR/install-agent.sh" "$TMP_DIR/$ASSET" "$CONFIG_SRC" + +detect_arch() { + machine="$(uname -m 2>/dev/null || echo unknown)" + case "$machine" in + x86_64|amd64) echo amd64 ;; + aarch64|arm64) echo arm64 ;; + armv7l|armv7*) echo armv7 ;; + mips64el|mipsle) echo mipsle ;; + mipsel|mips*) echo mipsle ;; + *) + echo "unsupported architecture: $machine" >&2 + exit 1 + ;; + esac +} + +download() { + url="$1" + dest="$2" + if command -v curl >/dev/null 2>&1; then + curl -fsSL "$url" -o "$dest" + return + fi + if command -v wget >/dev/null 2>&1; then + wget -qO "$dest" "$url" + return + fi + echo "need curl or wget" >&2 + exit 1 +} diff --git a/scripts/build-agent.ps1 b/scripts/build-agent.ps1 new file mode 100644 index 0000000..ce49ad9 --- /dev/null +++ b/scripts/build-agent.ps1 @@ -0,0 +1,50 @@ +param( + [string]$OutputDir = "dist", + [string]$Version = "" +) + +$ErrorActionPreference = "Stop" + +New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null + +if ([string]::IsNullOrWhiteSpace($Version)) { + $versionScript = Join-Path $PSScriptRoot "version.ps1" + if (Test-Path $versionScript) { + $Version = & $versionScript + } else { + $Version = "dev" + } +} + +$targets = @( + @{ Name = "linux-amd64"; GOOS = "linux"; GOARCH = "amd64"; GOARM = "" }, + @{ Name = "linux-arm64"; GOOS = "linux"; GOARCH = "arm64"; GOARM = "" }, + @{ Name = "linux-armv7"; GOOS = "linux"; GOARCH = "arm"; GOARM = "7" }, + @{ Name = "linux-mipsle"; GOOS = "linux"; GOARCH = "mipsle"; GOARM = ""; GOMIPS = "softfloat" } +) + +foreach ($target in $targets) { + $env:CGO_ENABLED = "0" + $env:GOOS = $target.GOOS + $env:GOARCH = $target.GOARCH + if ($target.GOARM) { + $env:GOARM = $target.GOARM + } else { + Remove-Item Env:\GOARM -ErrorAction SilentlyContinue + } + if ($target.GOMIPS) { + $env:GOMIPS = $target.GOMIPS + } else { + Remove-Item Env:\GOMIPS -ErrorAction SilentlyContinue + } + + $out = Join-Path $OutputDir "klipperanywhere-agent-$($target.Name)" + Write-Host "Building $out" + go build -ldflags "-X main.agentVersion=$Version" -o $out ./cmd/agent +} + +Remove-Item Env:\GOOS -ErrorAction SilentlyContinue +Remove-Item Env:\GOARCH -ErrorAction SilentlyContinue +Remove-Item Env:\GOARM -ErrorAction SilentlyContinue +Remove-Item Env:\GOMIPS -ErrorAction SilentlyContinue +Remove-Item Env:\CGO_ENABLED -ErrorAction SilentlyContinue diff --git a/scripts/build-release.sh b/scripts/build-release.sh new file mode 100644 index 0000000..f6867ec --- /dev/null +++ b/scripts/build-release.sh @@ -0,0 +1,14 @@ +#!/bin/sh +set -eu + +VERSION="${1:-${KA_VERSION:-dev}}" +OUT_DIR="${2:-dist}" + +mkdir -p "$OUT_DIR" + +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-X main.serverVersion=$VERSION" -o "$OUT_DIR/klipperanywhere-server-linux-amd64" ./cmd/server +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-X main.agentVersion=$VERSION" -o "$OUT_DIR/klipperanywhere-agent-linux-amd64" ./cmd/agent +CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-X main.agentVersion=$VERSION" -o "$OUT_DIR/klipperanywhere-agent-linux-arm64" ./cmd/agent +CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-X main.agentVersion=$VERSION" -o "$OUT_DIR/klipperanywhere-agent-linux-armv7" ./cmd/agent +CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags "-X main.agentVersion=$VERSION" -o "$OUT_DIR/klipperanywhere-agent-linux-mipsle" ./cmd/agent +printf '%s\n' "$VERSION" > "$OUT_DIR/VERSION.txt" diff --git a/scripts/install-agent-systemd.sh b/scripts/install-agent-systemd.sh new file mode 100644 index 0000000..b30379c --- /dev/null +++ b/scripts/install-agent-systemd.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu + +exec "$(dirname "$0")/install-agent.sh" "$@" diff --git a/scripts/install-agent.sh b/scripts/install-agent.sh new file mode 100644 index 0000000..185f2b5 --- /dev/null +++ b/scripts/install-agent.sh @@ -0,0 +1,96 @@ +#!/bin/sh +set -eu + +BIN_SRC="${1:-}" +CONFIG_SRC="${2:-}" + +if [ -z "$BIN_SRC" ] || [ -z "$CONFIG_SRC" ]; then + echo "usage: install-agent.sh " >&2 + exit 2 +fi + +if [ "$(id -u)" -ne 0 ]; then + echo "run as root" >&2 + exit 1 +fi + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) + +if [ ! -f "$BIN_SRC" ]; then + echo "missing agent binary: $BIN_SRC" >&2 + exit 1 +fi +if [ ! -f "$CONFIG_SRC" ]; then + echo "missing agent config: $CONFIG_SRC" >&2 + exit 1 +fi + +AGENT_DIR="/etc/klipperanywhere" +STATE_DIR="/var/lib/klipperanywhere" +ROLLBACK_DIR="$STATE_DIR/rollback" +AGENT_BIN="/usr/local/bin/klipperanywhere-agent" +AGENT_CFG="$AGENT_DIR/agent.json" +INITD_SCRIPT="/etc/init.d/klipperanywhere-agent" + +install -d "$AGENT_DIR" +install -d "$STATE_DIR" +install -d /usr/local/bin + +if [ -f "$AGENT_BIN" ] || [ -f "$AGENT_CFG" ]; then + install -d "$ROLLBACK_DIR" + if [ -f "$AGENT_BIN" ]; then + install -m 0755 "$AGENT_BIN" "$ROLLBACK_DIR/klipperanywhere-agent.bak" + fi + if [ -f "$AGENT_CFG" ]; then + install -m 0600 "$AGENT_CFG" "$ROLLBACK_DIR/agent.json.bak" + fi +fi + +install -m 0755 "$BIN_SRC" "$AGENT_BIN" +install -m 0600 "$CONFIG_SRC" "$AGENT_CFG" + +if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then + install -d /etc/systemd/system + install -m 0644 "$SCRIPT_DIR/../packaging/klipperanywhere-agent.service" /etc/systemd/system/klipperanywhere-agent.service + systemctl daemon-reload + systemctl enable klipperanywhere-agent + systemctl restart klipperanywhere-agent + systemctl status klipperanywhere-agent --no-pager + exit 0 +fi + +install -m 0755 "$SCRIPT_DIR/../packaging/klipperanywhere-agent.initd" "$INITD_SCRIPT" + +if command -v rc-update >/dev/null 2>&1; then + rc-update add klipperanywhere-agent default 2>/dev/null || true + rc-service klipperanywhere-agent restart 2>/dev/null || rc-service klipperanywhere-agent start + rc-service klipperanywhere-agent status || true + exit 0 +fi + +if command -v update-rc.d >/dev/null 2>&1; then + update-rc.d klipperanywhere-agent defaults 2>/dev/null || true + "$INITD_SCRIPT" restart + "$INITD_SCRIPT" status || true + exit 0 +fi + +if command -v chkconfig >/dev/null 2>&1; then + chkconfig --add klipperanywhere-agent 2>/dev/null || true + "$INITD_SCRIPT" restart + "$INITD_SCRIPT" status || true + exit 0 +fi + +for dir in /etc/rcS.d /etc/rc.d /etc/init.d; do + if [ -d "$dir" ]; then + ln -sf "$INITD_SCRIPT" "$dir/S99klipperanywhere-agent" + "$INITD_SCRIPT" restart + echo "Installed BusyBox-style startup hook at $dir/S99klipperanywhere-agent" + echo "If this host uses a different boot hook, run: $INITD_SCRIPT start" + exit 0 + fi +done + +echo "Installed agent binary and init script, but could not auto-enable it." +echo "Start it manually with: $INITD_SCRIPT start" diff --git a/scripts/uninstall-agent-systemd.sh b/scripts/uninstall-agent-systemd.sh new file mode 100644 index 0000000..0890890 --- /dev/null +++ b/scripts/uninstall-agent-systemd.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu + +exec "$(dirname "$0")/uninstall-agent.sh" "$@" diff --git a/scripts/uninstall-agent.sh b/scripts/uninstall-agent.sh new file mode 100644 index 0000000..0cdc044 --- /dev/null +++ b/scripts/uninstall-agent.sh @@ -0,0 +1,35 @@ +#!/bin/sh +set -eu + +if [ "$(id -u)" -ne 0 ]; then + echo "run as root" >&2 + exit 1 +fi + +if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then + systemctl stop klipperanywhere-agent 2>/dev/null || true + systemctl disable klipperanywhere-agent 2>/dev/null || true + rm -f /etc/systemd/system/klipperanywhere-agent.service + systemctl daemon-reload +fi + +if [ -x /etc/init.d/klipperanywhere-agent ]; then + /etc/init.d/klipperanywhere-agent stop 2>/dev/null || true +fi +rm -f /etc/init.d/klipperanywhere-agent +rm -f /etc/rcS.d/S99klipperanywhere-agent +rm -f /etc/rc.d/S99klipperanywhere-agent + +if command -v rc-update >/dev/null 2>&1; then + rc-update del klipperanywhere-agent default 2>/dev/null || true +fi +if command -v update-rc.d >/dev/null 2>&1; then + update-rc.d -f klipperanywhere-agent remove 2>/dev/null || true +fi +if command -v chkconfig >/dev/null 2>&1; then + chkconfig --del klipperanywhere-agent 2>/dev/null || true +fi + +rm -f /usr/local/bin/klipperanywhere-agent + +echo "Left /etc/klipperanywhere/agent.json in place." diff --git a/scripts/version.ps1 b/scripts/version.ps1 new file mode 100644 index 0000000..82380c1 --- /dev/null +++ b/scripts/version.ps1 @@ -0,0 +1,27 @@ +param() + +$ErrorActionPreference = "Stop" + +try { + $version = git describe --tags --always --dirty 2>$null + if ($LASTEXITCODE -eq 0 -and $version) { + Write-Output $version + exit 0 + } +} catch { +} + +try { + $version = git rev-parse --short HEAD 2>$null + if ($LASTEXITCODE -eq 0 -and $version) { + Write-Output $version + exit 0 + } +} catch { +} + +if ($env:KA_VERSION) { + Write-Output $env:KA_VERSION +} else { + Write-Output "dev" +} diff --git a/scripts/version.sh b/scripts/version.sh new file mode 100644 index 0000000..0648b3e --- /dev/null +++ b/scripts/version.sh @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu + +if command -v git >/dev/null 2>&1; then + if version="$(git describe --tags --always --dirty 2>/dev/null)"; then + printf '%s\n' "$version" + exit 0 + fi + if version="$(git rev-parse --short HEAD 2>/dev/null)"; then + printf '%s\n' "$version" + exit 0 + fi +fi + +printf '%s\n' "${KA_VERSION:-dev}" diff --git a/web/static/account.html b/web/static/account.html new file mode 100644 index 0000000..82285e8 --- /dev/null +++ b/web/static/account.html @@ -0,0 +1,89 @@ + + + + + + Account - KlipperAnywhere + + + + + + + + +
+ + + KlipperAnywhere + + +
+ +
+
+

Account settings

+

Account

+
+ + +
+ + + + + + diff --git a/web/static/account.js b/web/static/account.js new file mode 100644 index 0000000..683bdd2 --- /dev/null +++ b/web/static/account.js @@ -0,0 +1,114 @@ +const csrfMeta = document.getElementById("csrf-meta"); +const refresh = document.getElementById("refresh"); +const status = document.getElementById("account-status"); +const form = document.getElementById("account-form"); +const facts = document.getElementById("account-facts"); + +let sessionCSRF = csrfMeta ? csrfMeta.content : ""; + +async function loadSession() { + const response = await fetch("/api/session", { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return null; + } + const session = await response.json(); + if (!session.authenticated) { + window.location.href = "/login"; + return null; + } + if (session.csrf_token) { + sessionCSRF = session.csrf_token; + } + renderAccount(session); + return session; +} + +function renderAccount(session) { + facts.innerHTML = ` +
Username
${escapeHTML(session.username || "Unknown")}
+
Role
${escapeHTML(session.role || "user")}
+
Printer grants
${renderGrants(session.printer_grants || [])}
+ `; +} + +function renderGrants(grants) { + if (!grants.length) { + return "No printer access assigned."; + } + return grants.map((grant) => `${escapeHTML(grant.printer_id)} (${escapeHTML(grant.access || "read")})`).join("
"); +} + +async function apiRequest(url, method, body) { + const options = { + method, + credentials: "same-origin", + headers: { + "X-CSRF-Token": sessionCSRF, + }, + }; + if (body) { + options.headers["Content-Type"] = "application/json"; + options.body = JSON.stringify(body); + } + const response = await fetch(url, options); + if (!response.ok) { + const text = await response.text(); + throw new Error(text || `Request failed: ${response.status}`); + } + return response; +} + +function setStatus(message, isError = false) { + if (!message) { + status.hidden = true; + status.textContent = ""; + status.classList.remove("error", "success"); + return; + } + status.hidden = false; + status.textContent = message; + status.classList.toggle("error", isError); + status.classList.toggle("success", !isError); +} + +form.addEventListener("submit", async (event) => { + event.preventDefault(); + setStatus(""); + const data = new FormData(form); + const currentPassword = String(data.get("current_password") || ""); + const newPassword = String(data.get("new_password") || ""); + const confirmPassword = String(data.get("confirm_password") || ""); + if (newPassword !== confirmPassword) { + setStatus("New passwords do not match.", true); + return; + } + try { + await apiRequest("/api/account", "PATCH", { + current_password: currentPassword, + new_password: newPassword, + }); + form.reset(); + setStatus("Password updated.", false); + } catch (error) { + setStatus(error instanceof Error ? error.message : "Unable to update password.", true); + } +}); + +refresh.addEventListener("click", async () => { + setStatus(""); + await loadSession(); +}); + +function escapeHTML(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +(async () => { + await loadSession(); +})(); diff --git a/web/static/admin.html b/web/static/admin.html new file mode 100644 index 0000000..90727d9 --- /dev/null +++ b/web/static/admin.html @@ -0,0 +1,149 @@ + + + + + + Admin - KlipperAnywhere + + + + + + + +
+ + + KlipperAnywhere + + +
+ +
+
+

Administration

+

Admin

+
+ +
+
+
+

Admin tools

+

Manage printer installs, users, and audit history from one place.

+
+ Admin +
+
+
+ Printer setup + Install agent +

Connect to a printer host over SSH and install the agent.

+ +
+
+ Access + Manage users +

Create accounts, set roles, and assign printer grants.

+ +
+
+ Security + Audit log +

Review recent logins, account changes, printer access, and control actions.

+ +
+
+
+ +
+
+
+

Notifications

+

Configure Telegram delivery and bot commands separately.

+
+ Off +
+
+ + + + +

Leave the token blank to keep the saved value.

+

The test button uses the current form values without saving them.

+
+ + +
+

+
+
+ +
+
+
+

Versions

+

Current server build and connected agent versions.

+
+ Version +
+
+
Server build
Loading...
+
Available agent
Loading...
+
+
+ +
+
+
+

Connected printers

+

Upgrade or reinstall the agent for printers that are already connected.

+
+ 0 printers +
+
+
+
+ + + + + + diff --git a/web/static/admin.js b/web/static/admin.js new file mode 100644 index 0000000..72b0a09 --- /dev/null +++ b/web/static/admin.js @@ -0,0 +1,329 @@ +const adminInstallLink = document.getElementById("admin-install-link"); +const adminInstallCopy = document.getElementById("admin-install-copy"); +const adminContext = document.getElementById("admin-context"); +const adminNotificationsSummary = document.getElementById("admin-notifications-summary"); +const adminNotificationsPill = document.getElementById("admin-notifications-pill"); +const adminNotificationsForm = document.getElementById("admin-notifications-form"); +const adminTelegramEnabled = document.getElementById("admin-telegram-enabled"); +const adminTelegramCommandsEnabled = document.getElementById("admin-telegram-commands-enabled"); +const adminTelegramBotToken = document.getElementById("admin-telegram-bot-token"); +const adminTelegramChatID = document.getElementById("admin-telegram-chat-id"); +const adminTelegramTestButton = document.getElementById("admin-telegram-test"); +const adminTelegramTestResult = document.getElementById("admin-telegram-test-result"); +const adminServerVersion = document.getElementById("admin-server-version"); +const adminAvailableVersion = document.getElementById("admin-available-version"); +const adminPrinters = document.getElementById("admin-printers"); +const adminPrinterCount = document.getElementById("admin-printer-count"); +let adminTelegramTokenSet = false; + +function getCSRFToken() { + if (window.__KA_SESSION__ && window.__KA_SESSION__.csrf_token) { + return String(window.__KA_SESSION__.csrf_token); + } + const logoutField = document.getElementById("logout-csrf"); + return logoutField ? String(logoutField.value || "") : ""; +} + +function getPrinterID() { + const params = new URLSearchParams(window.location.search); + return (params.get("printer_id") || "").trim(); +} + +function updateContext() { + const printerID = getPrinterID(); + if (!printerID) { + if (adminInstallCopy) { + adminInstallCopy.textContent = "Connect to a printer host over SSH and install the agent."; + } + if (adminContext) { + adminContext.textContent = "Manage printer installs, users, and audit history from one place."; + } + if (adminInstallLink) { + adminInstallLink.href = "/install"; + } + return; + } + + const encoded = encodeURIComponent(printerID); + if (adminInstallLink) { + adminInstallLink.href = `/install?printer_id=${encoded}`; + } + if (adminInstallCopy) { + adminInstallCopy.textContent = `Install the agent for printer ${printerID}.`; + } + if (adminContext) { + adminContext.textContent = `Printer context detected for ${printerID}.`; + } +} + +function renderVersions(session) { + const version = String(session && session.server_version ? session.server_version : "dev"); + if (adminServerVersion) { + adminServerVersion.textContent = version; + } + if (adminAvailableVersion) { + adminAvailableVersion.textContent = version; + } +} + +async function loadNotificationSettings() { + if (!adminNotificationsForm) { + return; + } + try { + const response = await fetch("/api/notifications", { credentials: "same-origin" }); + if (!response.ok) { + if (adminNotificationsSummary) { + adminNotificationsSummary.textContent = `Unable to load notification settings (${response.status}).`; + } + return; + } + const payload = await response.json(); + const settings = payload.notifications || {}; + if (adminTelegramEnabled) { + adminTelegramEnabled.checked = Boolean(settings.telegram_enabled); + } + if (adminTelegramCommandsEnabled) { + adminTelegramCommandsEnabled.checked = Boolean(settings.telegram_commands_enabled); + } + if (adminTelegramBotToken) { + adminTelegramBotToken.value = String(settings.telegram_bot_token || ""); + adminTelegramBotToken.placeholder = "123456:ABCDEF"; + } + adminTelegramTokenSet = Boolean(String(settings.telegram_bot_token || "").trim()); + if (adminTelegramChatID) { + adminTelegramChatID.value = settings.telegram_chat_id || ""; + } + renderNotificationSummary(settings); + updateTelegramTestButtonState(); + } catch (error) { + if (adminNotificationsSummary) { + adminNotificationsSummary.textContent = "Unable to load notification settings."; + } + } +} + +async function saveNotificationSettings(event) { + event.preventDefault(); + if (!adminNotificationsForm) { + return; + } + const payload = { + telegram_enabled: Boolean(adminTelegramEnabled && adminTelegramEnabled.checked), + telegram_commands_enabled: Boolean(adminTelegramCommandsEnabled && adminTelegramCommandsEnabled.checked), + telegram_chat_id: adminTelegramChatID ? adminTelegramChatID.value : "", + }; + if (adminTelegramBotToken && adminTelegramBotToken.value.trim() !== "") { + payload.telegram_bot_token = adminTelegramBotToken.value.trim(); + } + const response = await fetch("/api/notifications", { + method: "PATCH", + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": getCSRFToken(), + }, + body: JSON.stringify(payload), + }); + if (!response.ok) { + const error = await response.text(); + if (adminNotificationsSummary) { + adminNotificationsSummary.textContent = error || `Failed to save notification settings (${response.status}).`; + } + return; + } + await loadNotificationSettings(); +} + +function renderNotificationSummary(settings) { + if (!adminNotificationsSummary || !adminNotificationsPill) { + return; + } + const enabled = Boolean(settings && settings.telegram_enabled); + const commandsEnabled = Boolean(settings && settings.telegram_commands_enabled); + const tokenSet = Boolean(String(settings && settings.telegram_bot_token ? settings.telegram_bot_token : "").trim()) || Boolean(settings && settings.telegram_bot_token_set); + const chatSet = Boolean(String(settings && settings.telegram_chat_id ? settings.telegram_chat_id : "").trim()); + const ready = (enabled || commandsEnabled) && tokenSet && chatSet; + adminNotificationsPill.textContent = ready ? "On" : "Off"; + adminNotificationsPill.classList.toggle("ok", ready); + adminNotificationsPill.classList.toggle("warn", !ready); + if (!enabled && !commandsEnabled) { + adminNotificationsSummary.textContent = "Telegram delivery and bot commands are disabled."; + } else if (!tokenSet || !chatSet) { + adminNotificationsSummary.textContent = "Telegram is enabled, but the bot token or chat ID is missing."; + } else if (enabled && commandsEnabled) { + adminNotificationsSummary.textContent = "Telegram delivery and bot commands are enabled."; + } else if (enabled) { + adminNotificationsSummary.textContent = "Telegram delivery is enabled; bot commands are disabled."; + } else { + adminNotificationsSummary.textContent = "Telegram bot commands are enabled; delivery is disabled."; + } +} + +function updateTelegramTestButtonState() { + if (!adminTelegramTestButton) { + return; + } + const tokenReady = Boolean(adminTelegramBotToken && adminTelegramBotToken.value.trim() !== ""); + const chatReady = Boolean(adminTelegramChatID && adminTelegramChatID.value.trim() !== ""); + adminTelegramTestButton.disabled = !(tokenReady && chatReady); +} + +function renderTelegramTestResult(text, kind) { + if (!adminTelegramTestResult) { + return; + } + adminTelegramTestResult.textContent = text; + adminTelegramTestResult.classList.remove("status-info", "status-ok", "status-error"); + if (kind) { + adminTelegramTestResult.classList.add(kind); + } +} + +async function sendTelegramTestNotification() { + if (!adminNotificationsForm) { + return; + } + const payload = { + telegram_enabled: Boolean(adminTelegramEnabled && adminTelegramEnabled.checked), + }; + const tokenValue = adminTelegramBotToken ? adminTelegramBotToken.value.trim() : ""; + if (tokenValue !== "") { + payload.telegram_bot_token = tokenValue; + } + const chatValue = adminTelegramChatID ? adminTelegramChatID.value.trim() : ""; + if (chatValue !== "") { + payload.telegram_chat_id = chatValue; + } + renderTelegramTestResult("Sending test notification...", "status-info"); + if (adminTelegramTestButton) { + adminTelegramTestButton.disabled = true; + } + try { + const response = await fetch("/api/notifications/test", { + method: "POST", + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": getCSRFToken(), + }, + body: JSON.stringify(payload), + }); + const text = await response.text(); + if (!response.ok) { + renderTelegramTestResult(text || `Failed to send test notification (${response.status}).`, "status-error"); + return; + } + let message = "Test notification sent."; + try { + const parsed = text ? JSON.parse(text) : {}; + if (parsed && parsed.message) { + message = String(parsed.message); + } + } catch (error) { + // Keep the fallback message. + } + renderTelegramTestResult(message, "status-ok"); + } catch (error) { + renderTelegramTestResult("Unable to send test notification.", "status-error"); + } finally { + updateTelegramTestButtonState(); + } +} + +async function loadPrinters() { + if (!adminPrinters) { + return; + } + try { + const response = await fetch("/api/printers", { credentials: "same-origin" }); + if (!response.ok) { + adminPrinters.innerHTML = `

Unable to load printers (${response.status}).

`; + if (adminPrinterCount) { + adminPrinterCount.textContent = "Unavailable"; + } + return; + } + const payload = await response.json(); + const printers = Array.isArray(payload.printers) ? payload.printers : []; + if (adminPrinterCount) { + adminPrinterCount.textContent = `${printers.length} printer${printers.length === 1 ? "" : "s"}`; + } + if (printers.length === 0) { + adminPrinters.innerHTML = `

No printers are connected right now.

`; + return; + } + const availableVersion = String((window.__KA_SESSION__ && window.__KA_SESSION__.server_version) || "dev"); + adminPrinters.innerHTML = printers.map((printer) => { + const settings = printer.settings || {}; + const health = printer.health || {}; + const printerID = String(printer.printer_id || ""); + const agentVersion = String(health.agent_version || "Unknown"); + const versionMatch = agentVersion && availableVersion && agentVersion === availableVersion; + const upgradeText = versionMatch ? "Reinstall" : "Upgrade"; + const upgradeLink = printerID ? `/install?printer_id=${encodeURIComponent(printerID)}` : "/install"; + return ` +
+
+ ${escapeHTML(settings.display_name || printerID || "Unknown printer")} +

${escapeHTML(printerID || "Unknown printer")}

+
+
+
Agent
${escapeHTML(agentVersion)}
+
Available
${escapeHTML(availableVersion)}
+
+ +
+ `; + }).join(""); + } catch (error) { + adminPrinters.innerHTML = `

Unable to load printers.

`; + if (adminPrinterCount) { + adminPrinterCount.textContent = "Unavailable"; + } + } +} + +window.__KA_SESSION_PROMISE__ = window.__KA_SESSION_PROMISE__ || Promise.resolve(); +window.__KA_SESSION_PROMISE__.finally(() => { + updateContext(); + renderVersions(window.__KA_SESSION__ || {}); + loadNotificationSettings(); + loadPrinters(); +}); + +if (adminNotificationsForm) { + adminNotificationsForm.addEventListener("submit", saveNotificationSettings); +} +if (adminTelegramBotToken) { + adminTelegramBotToken.addEventListener("input", updateTelegramTestButtonState); +} +if (adminTelegramChatID) { + adminTelegramChatID.addEventListener("input", updateTelegramTestButtonState); +} +if (adminTelegramCommandsEnabled) { + adminTelegramCommandsEnabled.addEventListener("change", () => { + renderNotificationSummary({ + telegram_enabled: Boolean(adminTelegramEnabled && adminTelegramEnabled.checked), + telegram_commands_enabled: Boolean(adminTelegramCommandsEnabled && adminTelegramCommandsEnabled.checked), + telegram_bot_token: adminTelegramBotToken ? adminTelegramBotToken.value : "", + telegram_bot_token_set: Boolean(adminTelegramBotToken && adminTelegramBotToken.value.trim() !== ""), + telegram_chat_id: adminTelegramChatID ? adminTelegramChatID.value : "", + }); + }); +} +if (adminTelegramTestButton) { + adminTelegramTestButton.addEventListener("click", sendTelegramTestNotification); +} + +function escapeHTML(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} diff --git a/web/static/assets/favicon.png b/web/static/assets/favicon.png new file mode 100644 index 0000000..a94a89a Binary files /dev/null and b/web/static/assets/favicon.png differ diff --git a/web/static/assets/hero-printer.png b/web/static/assets/hero-printer.png new file mode 100644 index 0000000..5af1d29 Binary files /dev/null and b/web/static/assets/hero-printer.png differ diff --git a/web/static/audit.html b/web/static/audit.html new file mode 100644 index 0000000..11a6434 --- /dev/null +++ b/web/static/audit.html @@ -0,0 +1,64 @@ + + + + + + Audit - KlipperAnywhere + + + + + + + + +
+ + + KlipperAnywhere + + +
+ +
+
+

Security trail

+

Audit log

+
+ +
+
+

Recent events

+ JSON +
+

Loading audit events...

+
+
+
+ + + + + + + diff --git a/web/static/audit.js b/web/static/audit.js new file mode 100644 index 0000000..e82349a --- /dev/null +++ b/web/static/audit.js @@ -0,0 +1,78 @@ +const refresh = document.getElementById("refresh"); +const status = document.getElementById("audit-status"); +const list = document.getElementById("audit-list"); + +async function loadAudit() { + setStatus("Loading audit events..."); + list.innerHTML = ""; + const response = await fetch("/api/audit?limit=100", { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return; + } + if (response.status === 403) { + window.location.href = "/dashboard"; + return; + } + if (!response.ok) { + setStatus("Unable to load audit events.", true); + return; + } + const data = await response.json(); + const events = data.events || []; + if (events.length === 0) { + setStatus("No audit events yet."); + return; + } + setStatus(""); + list.innerHTML = events.map(renderEvent).join(""); +} + +function renderEvent(event) { + const timestamp = event.timestamp ? new Date(event.timestamp).toLocaleString() : "Unknown"; + const parts = [ + event.actor ? `${escapeHTML(event.actor)}` : "system", + `${escapeHTML(event.action || "event")}`, + event.printer_id ? `${escapeHTML(event.printer_id)}` : "", + event.target_id ? `${escapeHTML(event.target_id)}` : "", + event.method ? `${escapeHTML(event.method)}` : "", + event.path ? `${escapeHTML(event.path)}` : "", + ].filter(Boolean); + return ` +
+
+ ${escapeHTML(timestamp)} + ${escapeHTML(event.action || "event")} +
+
+ ${parts.join("")} +
+ ${event.detail ? `

${escapeHTML(event.detail)}

` : ""} + ${event.status ? `

Status ${escapeHTML(String(event.status))}

` : ""} +
+ `; +} + +function setStatus(message, isError = false) { + if (!message) { + status.hidden = true; + status.textContent = ""; + return; + } + status.hidden = false; + status.textContent = message; + status.classList.toggle("error", isError); + status.classList.toggle("success", !isError); +} + +function escapeHTML(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +refresh.addEventListener("click", loadAudit); +loadAudit(); diff --git a/web/static/dashboard.html b/web/static/dashboard.html new file mode 100644 index 0000000..d260164 --- /dev/null +++ b/web/static/dashboard.html @@ -0,0 +1,57 @@ + + + + + + Dashboard - KlipperAnywhere + + + + + + + +
+ + + KlipperAnywhere + + +
+ +
+
+

Connected printers

+

Dashboard

+
+ +
+

Loading printers...

+
+
+ + + + + + diff --git a/web/static/dashboard.js b/web/static/dashboard.js new file mode 100644 index 0000000..631c699 --- /dev/null +++ b/web/static/dashboard.js @@ -0,0 +1,309 @@ +const grid = document.getElementById("printer-grid"); +const refresh = document.getElementById("refresh"); + +async function loadPrinters() { + grid.innerHTML = '

Loading printers...

'; + + const response = await fetch("/api/printers", { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return; + } + if (!response.ok) { + grid.innerHTML = '

Unable to load printers.

'; + return; + } + + const data = await response.json(); + const printers = data.printers || []; + if (printers.length === 0) { + grid.innerHTML = '

No agents are connected.

'; + return; + } + + grid.innerHTML = printers.map(renderPrinter).join(""); +} + +function renderPrinter(printer) { + const health = printer.health || {}; + const settings = printer.settings || {}; + const session = window.__KA_SESSION__ || {}; + const reachable = health.moonraker_reachable === true; + const state = health.moonraker_state || "unknown"; + const message = health.moonraker_message || "No status message yet."; + const checked = health.checked_at_unix ? relativeTime(health.checked_at_unix) : "Waiting for heartbeat"; + const uiReachable = health.ui_reachable === true; + const label = settings.display_name || printer.printer_id; + const camera = (health.cameras || []).find((item) => item.has_snapshot === true); + const mmuMaterials = formatMmuMaterialsHtml(health.print_status); + const temperatureSummary = formatTemperatureSummary(health.print_status); + const thumbnail = camera + ? `${escapeHTML(printer.printer_id)} camera snapshot` + : '
No camera
'; + + return ` +
+ ${thumbnail} +
+
+ ${reachable ? "Reachable" : "Not reachable"} +

${escapeHTML(label)}

+ ${label !== printer.printer_id ? `

${escapeHTML(printer.printer_id)}

` : ""} +
+
+
+
+
Agent
+
${printer.connected ? "Connected" : "Disconnected"}
+
+
+
Moonraker
+
${escapeHTML(state)}
+
+
+
Message
+
${escapeHTML(message)}
+
+
+
Last heartbeat
+
${escapeHTML(checked)}
+
+ ${temperatureSummary ? ` +
+
Temps
+
${escapeHTML(temperatureSummary)}
+
` : ""} + ${mmuMaterials ? ` +
+
MMU materials
+
${mmuMaterials}
+
` : ""} +
+ +
+ `; +} + +function relativeTime(unixSeconds) { + const seconds = Math.max(0, Math.floor(Date.now() / 1000) - unixSeconds); + if (seconds < 5) { + return "just now"; + } + if (seconds < 60) { + return `${seconds}s ago`; + } + const minutes = Math.floor(seconds / 60); + if (minutes < 60) { + return `${minutes}m ago`; + } + const hours = Math.floor(minutes / 60); + return `${hours}h ago`; +} + +function escapeHTML(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +function formatMmuMaterialsHtml(printStatus) { + if (!printStatus || typeof printStatus !== "object") { + return ""; + } + const state = collectMmuMaterialState(printStatus); + if (!state.visible) { + return ""; + } + if (state.disabled) { + return `${escapeHTML(state.label)}: disabled`; + } + if (state.rows.length === 0) { + return `${escapeHTML(state.label)}: enabled`; + } + return [ + ...state.rows.map((row) => mmuMaterialRowHtml(row)), + ].join(""); +} + +function collectMmuMaterialState(printStatus) { + const mmu = printStatus.moonraker_status && printStatus.moonraker_status.mmu; + if (!mmu || typeof mmu !== "object" || !Object.prototype.hasOwnProperty.call(mmu, "enabled")) { + return { visible: false, disabled: false, label: "MMU", rows: [] }; + } + const machine = printStatus.moonraker_status && printStatus.moonraker_status.mmu_machine; + const enabled = isTruthyMetadataValue(mmu.enabled); + const label = machine?.unit_0?.name || "MMU"; + if (!enabled) { + return { visible: true, disabled: true, label, rows: [] }; + } + const names = normalizeMetadataList(mmu.gate_filament_name); + const materials = normalizeMetadataList(mmu.gate_material); + const colors = normalizeMetadataList(mmu.gate_color); + const count = Math.max(names.length, materials.length, colors.length, Number(mmu.num_gates || 0)); + if (count === 0) { + return { visible: true, disabled: false, label, rows: [{ label, value: "Enabled", color: "" }] }; + } + return { + visible: true, + disabled: false, + label, + rows: Array.from({ length: count }, (_, index) => { + const parts = []; + let color = ""; + if (names[index] && names[index] !== "Unknown") { + parts.push(String(names[index])); + } + if (materials[index] && materials[index] !== names[index]) { + parts.push(`(${String(materials[index])})`); + } + if (colors[index]) { + color = String(colors[index]).replace(/[^0-9a-fA-F]/g, ""); + } + return { + label: `Gate ${index + 1}`, + value: parts.join(" ") || "Unknown material", + color, + }; + }), + }; +} + +function normalizeMetadataList(value) { + if (Array.isArray(value)) { + return value.filter((item) => item !== null && item !== undefined && item !== ""); + } + if (value === null || value === undefined || value === "") { + return []; + } + return [value]; +} + +function isTruthyMetadataValue(value) { + if (Array.isArray(value)) { + return value.length > 0; + } + if (typeof value === "string") { + const normalized = value.trim().toLowerCase(); + return normalized === "1" || normalized === "true" || normalized === "yes"; + } + return Boolean(value); +} + +function mmuMaterialRowHtml(row) { + const label = escapeHTML(row.label); + const value = row.value ? escapeHTML(row.value) : ""; + const color = row.color ? mmuNormalizeHexColor(row.color) : ""; + const swatchStyle = color ? ` style="--mmu-swatch:${escapeHTML(color)}"` : ""; + return `${label}${value ? ` ${value}` : ""}`; +} + +function mmuNormalizeHexColor(value) { + const raw = String(value || "").trim().replace(/[^0-9a-fA-F]/g, ""); + if (raw.length === 8) { + return `#${raw.slice(0, 6)}`; + } + if (raw.length === 6) { + return `#${raw}`; + } + if (raw.length === 3) { + return `#${raw.split("").map((ch) => ch + ch).join("")}`; + } + return ""; +} + +function formatTemperatureSummary(printStatus) { + const state = collectTemperatureState(printStatus); + if (!state.visible) { + return ""; + } + return state.rows.map((row) => `${row.label} ${row.value}`).join(" ยท "); +} + +function collectTemperatureState(printStatus) { + const status = printStatus && printStatus.moonraker_status; + if (!status || typeof status !== "object") { + return { visible: false, rows: [] }; + } + const rows = []; + const seen = new Set(); + const add = (key, label) => { + if (!Object.prototype.hasOwnProperty.call(status, key)) { + return; + } + const sensor = status[key]; + if (!sensor || typeof sensor !== "object") { + return; + } + const reading = formatTemperatureReading(sensor); + if (!reading) { + return; + } + rows.push({ label, value: reading }); + seen.add(key); + }; + add("extruder", "Hotend"); + add("heater_bed", "Bed"); + add("temperature_sensor chamber", "Chamber"); + Object.keys(status).sort().forEach((key) => { + if (seen.has(key) || !isTemperatureSensorKey(key)) { + return; + } + const sensor = status[key]; + if (!sensor || typeof sensor !== "object") { + return; + } + const reading = formatTemperatureReading(sensor); + if (!reading) { + return; + } + rows.push({ label: prettifyTemperatureLabel(key), value: reading }); + }); + return { visible: rows.length > 0, rows }; +} + +function isTemperatureSensorKey(key) { + return typeof key === "string" && ( + key.startsWith("temperature_sensor ") || + key.startsWith("temperature_fan ") || + key.startsWith("temperature_probe ") + ); +} + +function prettifyTemperatureLabel(key) { + const raw = String(key || "") + .replace(/^temperature_(sensor|fan|probe)\s+/i, "") + .replace(/_/g, " ") + .trim(); + if (!raw) { + return "Sensor"; + } + return raw.replace(/\b\w/g, (ch) => ch.toUpperCase()); +} + +function formatTemperatureReading(sensor) { + const current = Number(sensor.temperature); + if (!Number.isFinite(current)) { + return ""; + } + const target = Number(sensor.target); + if (Number.isFinite(target) && target > 0) { + return `${current.toFixed(1)} / ${target.toFixed(1)}ยฐC`; + } + return `${current.toFixed(1)}ยฐC`; +} + +refresh.addEventListener("click", loadPrinters); +const sessionReady = window.__KA_SESSION_PROMISE__ || Promise.resolve(); +sessionReady.finally(() => { + loadPrinters(); + setInterval(loadPrinters, 15000); +}); diff --git a/web/static/index.html b/web/static/index.html new file mode 100644 index 0000000..e2cd648 --- /dev/null +++ b/web/static/index.html @@ -0,0 +1,70 @@ + + + + + + KlipperAnywhere + + + + + + + + + +
+
+ A modern 3D printer in a tidy workshop with a remote monitoring dashboard nearby. + +
+

Open-source remote access for Klipper

+

KlipperAnywhere

+

A self-hosted tunnel for Moonraker, printer UIs, and camera access without opening inbound ports on your printer network.

+ +
+
+ +
+
+ Tunnel + Outbound agent +

Printer-side connection over WebSocket.

+
+
+ Target + Moonraker first +

HTTP proxying and health heartbeats are in place.

+
+
+ Install + Small Go binary +

Designed for Raspberry Pi and rooted printer hosts.

+
+
+
+ + + diff --git a/web/static/install.html b/web/static/install.html new file mode 100644 index 0000000..d681406 --- /dev/null +++ b/web/static/install.html @@ -0,0 +1,124 @@ + + + + + + Install Printer - KlipperAnywhere + + + + + + + + +
+ + + KlipperAnywhere + + +
+ +
+
+

Printer setup

+

Install agent over SSH

+
+ +
+
+
+

Connection

+
+

Connect to the printer host, upload the installer, and start the agent without touching the host manually.

+

Use a root account or a user with passwordless sudo. If you opened this from a printer page, the printer ID will prefill.

+ +
+ + +

Use the URL the printer can reach from its own network, not 127.0.0.1 or localhost.

+ + + + + +

Choose Rinkhals only if the printer host runs the Rinkhals app framework. Standard installs use a service or init script.

+ + + + +
+
+ +
+
+

Result

+
+

The installer uploads the bootstrap scripts, generates the agent config, and runs the remote setup flow.

+
+
Status
Waiting
+
+
No install has been run yet.
+
+
+
+ + + + + + diff --git a/web/static/install.js b/web/static/install.js new file mode 100644 index 0000000..c99430f --- /dev/null +++ b/web/static/install.js @@ -0,0 +1,419 @@ +const csrfMeta = document.getElementById("csrf-meta"); +const refresh = document.getElementById("refresh"); +const form = document.getElementById("install-form"); +const status = document.getElementById("install-status"); +const facts = document.getElementById("install-facts"); +const output = document.getElementById("install-output"); +const serverURLInput = form ? form.querySelector("input[name='server_url']") : null; +const printerIDInput = form ? form.querySelector("input[name='printer_id']") : null; +const hostTypeInput = form ? form.querySelector("select[name='host_type']") : null; +const passwordInput = form ? form.querySelector("input[name='password']") : null; + +let sessionCSRF = csrfMeta ? csrfMeta.content : ""; +const installContext = new URL(window.location.href); +let activeInstallJobID = ""; +let activeInstallPollTimer = null; + +if (serverURLInput && !serverURLInput.value) { + const host = window.location.hostname; + if (host !== "localhost" && host !== "127.0.0.1" && host !== "::1") { + serverURLInput.value = window.location.origin; + } +} + if (printerIDInput && !printerIDInput.value) { + const printerID = installContext.searchParams.get("printer_id"); + if (printerID) { + printerIDInput.value = printerID; + } + } +if (hostTypeInput) { + const hostType = installContext.searchParams.get("host_type"); + if (hostType) { + hostTypeInput.value = hostType; + } +} + if (passwordInput && !passwordInput.value && printerIDInput && printerIDInput.value) { + try { + const storedPassword = sessionStorage.getItem(`ka-ssh-password:${printerIDInput.value.trim()}`) || ""; + if (storedPassword) { + passwordInput.value = storedPassword; + } + } catch { + // Ignore session storage failures. + } +} +if (serverURLInput && !serverURLInput.value) { + const serverURL = installContext.searchParams.get("server_url"); + if (serverURL) { + serverURLInput.value = serverURL; + } +} + +function setStatus(message, isError = false) { + if (!status) { + return; + } + if (!message) { + status.hidden = true; + status.textContent = ""; + status.className = "form-message"; + return; + } + status.hidden = false; + status.textContent = message; + status.className = isError ? "form-message error" : "form-message success"; +} + +async function loadSession() { + const response = await fetch("/api/session", { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return null; + } + const session = await response.json(); + if (!session.authenticated) { + window.location.href = "/login"; + return null; + } + if (session.is_admin !== true) { + window.location.href = "/dashboard"; + return null; + } + if (session.csrf_token) { + sessionCSRF = session.csrf_token; + } + return session; +} + +async function preloadInstallDetails() { + if (!printerIDInput || !printerIDInput.value) { + return; + } + const printerID = printerIDInput.value.trim(); + if (!printerID) { + return; + } + try { + const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}/settings`, { + credentials: "same-origin", + }); + if (!response.ok) { + return; + } + const payload = await response.json(); + const install = payload && payload.settings ? payload.settings.install : null; + if (!install) { + return; + } + if (serverURLInput && !serverURLInput.value && install.server_url) { + serverURLInput.value = install.server_url; + } + const hostInput = form ? form.querySelector("input[name='host']") : null; + const portInput = form ? form.querySelector("input[name='port']") : null; + const usernameInput = form ? form.querySelector("input[name='username']") : null; + const moonrakerInput = form ? form.querySelector("input[name='moonraker_url']") : null; + const uiURLInput = form ? form.querySelector("input[name='ui_url']") : null; + const uiAutoDetectInput = form ? form.querySelector("input[name='ui_auto_detect']") : null; + const hostTypeSelect = form ? form.querySelector("select[name='host_type']") : null; + if (hostInput && !hostInput.value && install.host) { + hostInput.value = install.host; + } + if (portInput && !portInput.value && install.port) { + portInput.value = String(install.port); + } + if (usernameInput && !usernameInput.value && install.username) { + usernameInput.value = install.username; + } + if (moonrakerInput && !moonrakerInput.value && install.moonraker_url) { + moonrakerInput.value = install.moonraker_url; + } + if (uiURLInput && !uiURLInput.value && install.ui_url) { + uiURLInput.value = install.ui_url; + } + if (uiAutoDetectInput && install.ui_auto_detect !== undefined) { + uiAutoDetectInput.checked = Boolean(install.ui_auto_detect); + } + if (hostTypeSelect && install.host_type) { + hostTypeSelect.value = String(install.host_type); + } + } catch { + return; + } +} + +async function runInstall(event) { + event.preventDefault(); + clearInstallPollTimer(); + activeInstallJobID = ""; + const data = new FormData(form); + const serverURLResult = validateServerURL(String(data.get("server_url") || "").trim()); + if (!serverURLResult.ok) { + setStatus(serverURLResult.error, true); + if (output) { + output.textContent = serverURLResult.error; + } + return; + } + if (serverURLInput) { + serverURLInput.value = serverURLResult.value; + } + + setStatus("Installing printer agent...", false); + if (facts) { + facts.innerHTML = `
Status
Installing
`; + } + const payload = { + host: String(data.get("host") || "").trim(), + server_url: serverURLResult.value, + port: Number(data.get("port") || 22), + username: String(data.get("username") || "").trim(), + password: String(data.get("password") || ""), + host_type: String(data.get("host_type") || "standard").trim() || "standard", + printer_id: String(data.get("printer_id") || "").trim(), + moonraker_url: String(data.get("moonraker_url") || "").trim(), + ui_url: String(data.get("ui_url") || "").trim(), + ui_auto_detect: Boolean(data.get("ui_auto_detect")), + }; + try { + const response = await fetch("/api/install/ssh", { + method: "POST", + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": sessionCSRF, + }, + body: JSON.stringify(payload), + }); + const text = await response.text(); + let body = null; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = null; + } + if (response.status === 202 || (response.ok && body && body.job_id)) { + const jobID = body?.job_id || ""; + if (!jobID) { + const message = "Installer job started but no job ID was returned."; + setStatus(message, true); + if (output) { + output.textContent = message; + } + return; + } + activeInstallJobID = jobID; + setStatus(body?.message || "Installer job started.", false); + renderInstallJob({ + id: jobID, + status: body?.status || "queued", + stage: body?.status || "queued", + message: body?.message || "Queued installer job.", + steps: [{ + at: new Date().toISOString(), + stage: body?.status || "queued", + message: body?.message || "Queued installer job.", + }], + output: body?.message || "Queued installer job.", + }, true); + pollInstallJob(jobID); + return; + } + if (!response.ok) { + const message = body && body.error ? body.error : text || `Install failed (${response.status})`; + setStatus(message, true); + if (output) { + output.textContent = text || message; + } + if (facts) { + facts.innerHTML = `
Status
Failed
`; + } + return; + } + if (body) { + renderInstallJob({ + id: body.job_id || "", + status: "failed", + stage: "failed", + message: body.error || `Install failed (${response.status})`, + output: text || body.error || "", + }, true); + } + } catch (error) { + const message = error instanceof Error ? error.message : "Unable to install printer agent."; + setStatus(message, true); + if (output) { + output.textContent = message; + } + if (facts) { + facts.innerHTML = `
Status
Failed
`; + } + } +} + +async function pollInstallJob(jobID) { + clearInstallPollTimer(); + if (!jobID) { + return; + } + try { + const response = await fetch(`/api/install/ssh/jobs/${encodeURIComponent(jobID)}`, { + credentials: "same-origin", + }); + if (!response.ok) { + const text = await response.text(); + setStatus(text || `Install job poll failed (${response.status})`, true); + if (output) { + output.textContent = text || `Install job poll failed (${response.status})`; + } + return; + } + const job = await response.json(); + renderInstallJob(job, false); + if (job && (job.status === "queued" || job.status === "running")) { + activeInstallPollTimer = window.setTimeout(() => { + pollInstallJob(jobID); + }, 1000); + return; + } + if (job && job.result) { + renderInstallResponse(job.result); + } + } catch (error) { + const message = error instanceof Error ? error.message : "Unable to poll installer job."; + setStatus(message, true); + if (output) { + output.textContent = message; + } + } +} + +function renderInstallJob(job, immediate = false) { + if (!job) { + return; + } + const statusLabel = String(job.status || "queued"); + const stageLabel = String(job.stage || statusLabel); + const message = String(job.message || ""); + const lines = []; + if (job.steps && job.steps.length) { + for (const step of job.steps) { + const stamp = step.at ? new Date(step.at).toLocaleTimeString() : ""; + const prefix = step.stage ? `[${step.stage}]` : "[step]"; + lines.push(`${stamp} ${prefix} ${step.message || ""}`.trim()); + } + } else if (job.output) { + const extra = String(job.output).trim(); + if (extra) { + lines.push(extra); + } + } + if (facts) { + facts.innerHTML = [ + fact("Status", capitalize(statusLabel)), + fact("Stage", stageLabel), + fact("Message", message || "Waiting for installer output."), + fact("Printer", job.printer_id || printerIDInput?.value || "unknown"), + fact("Host", job.host ? `${job.host}:${job.port || 22}` : String(form?.querySelector("input[name='host']")?.value || "unknown")), + fact("Host type", job.host_type || String(form?.querySelector("select[name='host_type']")?.value || "standard")), + ].join(""); + } + if (output) { + output.textContent = lines.length ? lines.join("\n") : (message || "Waiting for installer output."); + output.scrollTop = output.scrollHeight; + } + if (message) { + setStatus(message, statusLabel === "failed"); + } else if (!immediate) { + setStatus(statusLabel === "running" ? "Installer is still running..." : "Installer job queued.", false); + } +} + +function renderInstallResponse(body) { + const printerID = body?.printer_id || String(printerIDInput?.value || "unknown"); + const postInstallState = body?.post_install_connected === true ? "Confirmed" : "Pending"; + const postInstallMessage = body?.post_install_message || "Waiting for agent callback."; + setStatus(body?.post_install_connected === true + ? `Installed agent for ${printerID} and confirmed callback.` + : `Installed agent for ${printerID}. Waiting for callback.`, false); + if (facts) { + facts.innerHTML = [ + fact("Status", "Installed"), + fact("Printer", printerID), + fact("Host", `${body?.host || String(form?.querySelector("input[name='host']")?.value || "unknown")}:${body?.port || Number(form?.querySelector("input[name='port']")?.value || 22)}`), + fact("Host type", body?.host_type || String(form?.querySelector("select[name='host_type']")?.value || "standard")), + fact("Remote host", body?.remote_host || "unknown"), + fact("Server", body?.server_url || String(form?.querySelector("input[name='server_url']")?.value || "unknown")), + fact("Binary", body?.binary_source || "unknown"), + fact("Config", body?.config_path || "unknown"), + fact("Post-install", postInstallState), + fact("Callback", postInstallMessage), + fact("Rollback", body?.rollback_performed ? "Available" : "Not needed"), + fact("Rollback detail", body?.rollback_message || "None"), + ].join(""); + } + if (output) { + output.textContent = JSON.stringify(body || {}, null, 2); + output.scrollTop = output.scrollHeight; + } + if (passwordInput && passwordInput.value) { + try { + const pid = String(printerIDInput && printerIDInput.value ? printerIDInput.value.trim() : ""); + if (pid) { + sessionStorage.setItem(`ka-ssh-password:${pid}`, passwordInput.value); + } + } catch { + // Ignore session storage failures. + } + } +} + +function clearInstallPollTimer() { + if (activeInstallPollTimer) { + window.clearTimeout(activeInstallPollTimer); + activeInstallPollTimer = null; + } +} + +function capitalize(value) { + const text = String(value || ""); + if (!text) { + return ""; + } + return text.charAt(0).toUpperCase() + text.slice(1); +} + +function fact(label, value) { + return `
${escapeHTML(label)}
${escapeHTML(value)}
`; +} + +function validateServerURL(value) { + if (!value) { + return { ok: false, error: "Server URL is required." }; + } + try { + const url = new URL(value); + if (url.protocol !== "http:" && url.protocol !== "https:") { + return { ok: false, error: "Server URL must start with http:// or https://." }; + } + const host = url.hostname.toLowerCase(); + if (host === "localhost" || host === "127.0.0.1" || host === "::1") { + return { ok: false, error: "Server URL must be reachable from the printer host." }; + } + return { ok: true, value: url.origin.replace(/\/$/, "") }; + } catch { + return { ok: false, error: "Server URL must be a valid http:// or https:// URL." }; + } +} + +function escapeHTML(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +refresh.addEventListener("click", () => window.location.reload()); +form.addEventListener("submit", runInstall); +loadSession().then(() => preloadInstallDetails()); diff --git a/web/static/login.html b/web/static/login.html new file mode 100644 index 0000000..67c4bbc --- /dev/null +++ b/web/static/login.html @@ -0,0 +1,46 @@ + + + + + + Sign in - KlipperAnywhere + + + + + + + +
+ + + KlipperAnywhere + + +
+

Private access

+

Sign in

+

Access connected printers, health checks, and proxied Moonraker endpoints.

+ + + + +
+
+ + + diff --git a/web/static/printer-agent.html b/web/static/printer-agent.html new file mode 100644 index 0000000..633f490 --- /dev/null +++ b/web/static/printer-agent.html @@ -0,0 +1,188 @@ + + + + + + Agent - KlipperAnywhere + + + + + + + +
+ + + KlipperAnywhere + + +
+ +
+
+
+

Printer agent

+

Loading...

+
+ Checking +
+ +
+
+
+

Agent

+ JSON +
+
+
Agent
Loading...
+
+
+ +
+
+

Connectivity

+
+
+
Moonraker
Loading...
+
+
+ +
+
+

UI

+
+
+
UI
Loading...
+
+
+ +
+
+

Settings Sync

+ Edit +
+

Waiting for printer heartbeat.

+
+
Control mode
Loading...
+
+
+ +
+
+

Install Details

+ Install +
+

No install details saved yet.

+

Checking update status...

+ +
+
Status
Waiting...
+
+
+ + + Reinstall via SSH +
+
+ +
+
+

Rinkhals App

+ Raw +
+

Not using the Rinkhals app runtime.

+
+
Runtime
Not applicable
+
+
+ +
+
+

Install History

+ Raw +
+
+

No install history saved yet.

+
+
+ +
+
+

Print Status

+ Raw +
+ +
+ +
+
+

Raw Moonraker

+ Raw +
+

Waiting for printer data.

+
+
Raw keys
Waiting...
+
+
Waiting for Moonraker status...
+
+ +
+
+

Cameras

+ Raw +
+
+

Waiting for camera configuration...

+
+
+
+
+ + + + + + + + diff --git a/web/static/printer-agent.js b/web/static/printer-agent.js new file mode 100644 index 0000000..ea03053 --- /dev/null +++ b/web/static/printer-agent.js @@ -0,0 +1,807 @@ +const refresh = document.getElementById("refresh"); +const title = document.getElementById("printer-title"); +const status = document.getElementById("printer-status"); +const agentFacts = document.getElementById("agent-facts"); +const connectivityFacts = document.getElementById("connectivity-facts"); +const uiFacts = document.getElementById("ui-facts"); +const syncFacts = document.getElementById("sync-facts"); +const syncSummary = document.getElementById("sync-summary"); +const installSummary = document.getElementById("install-summary"); +const installVersionSummary = document.getElementById("install-version-summary"); +const installMessage = document.getElementById("install-message"); +const installFacts = document.getElementById("install-facts"); +const rinkhalsSummary = document.getElementById("rinkhals-summary"); +const rinkhalsFacts = document.getElementById("rinkhals-facts"); +const rinkhalsLink = document.getElementById("rinkhals-link"); +const installHistoryList = document.getElementById("install-history-list"); +const printStatusFacts = document.getElementById("print-status-facts"); +const moonrakerRawFacts = document.getElementById("moonraker-raw-facts"); +const moonrakerRawSummary = document.getElementById("moonraker-raw-summary"); +const moonrakerRawJson = document.getElementById("moonraker-raw-json"); +const cameraList = document.getElementById("camera-list"); +const healthLink = document.getElementById("health-link"); +const printStatusLink = document.getElementById("print-status-link"); +const moonrakerRawLink = document.getElementById("moonraker-raw-link"); +const cameraLink = document.getElementById("camera-link"); +const settingsLink = document.getElementById("settings-link"); +const settingsEditLink = document.getElementById("settings-edit-link"); +const installLink = document.getElementById("install-link"); +const installAction = document.getElementById("install-action"); +const upgradeNow = document.getElementById("upgrade-now"); +const updateCheck = document.getElementById("update-check"); +const installHistoryLink = document.getElementById("install-history-link"); +const sshPasswordModal = document.getElementById("ssh-password-modal"); +const sshPasswordInput = document.getElementById("ssh-password-input"); +const sshPasswordCancel = document.getElementById("ssh-password-cancel"); +const sshPasswordContinue = document.getElementById("ssh-password-continue"); +const uiLink = document.getElementById("ui-link"); +const backLink = document.getElementById("back-link"); +const logoutCSRF = document.getElementById("logout-csrf"); +const adminLink = document.getElementById("admin-link"); + +const printerID = decodeURIComponent(window.location.pathname.replace(/^\/printers\//, "").replace(/\/agent\/?$/, "")); +let lastData = null; +let pendingReinstallURL = ""; + +if (printerID) { + const encoded = encodeURIComponent(printerID); + if (backLink) { + backLink.href = `/printers/${encoded}`; + } + if (settingsLink) { + settingsLink.href = `/printers/${encoded}/settings`; + } + if (settingsEditLink) { + settingsEditLink.href = `/printers/${encoded}/settings`; + } + if (uiLink) { + uiLink.href = `/printers/${encoded}/ui/`; + } + if (healthLink) { + healthLink.href = `/api/printers/${encoded}`; + } + if (printStatusLink) { + printStatusLink.href = `/p/${encoded}/moonraker/printer/objects/query?print_stats&display_status&gcode_move&toolhead`; + } + if (moonrakerRawLink) { + moonrakerRawLink.href = `/p/${encoded}/moonraker/printer/objects/query?print_stats&display_status&gcode_move&toolhead`; + } + if (cameraLink) { + cameraLink.href = `/p/${encoded}/moonraker/server/webcams/list`; + } + if (adminLink) { + adminLink.href = `/admin?printer_id=${encoded}`; + } + if (installLink) { + installLink.href = `/install?printer_id=${encoded}`; + } + if (installAction) { + installAction.href = `/install?printer_id=${encoded}`; + } + if (installHistoryLink) { + installHistoryLink.href = `/api/printers/${encoded}`; + } + if (rinkhalsLink) { + rinkhalsLink.href = `/api/printers/${encoded}`; + } +} + +async function loadSession() { + const response = await fetch("/api/session", { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return; + } + const session = await response.json(); + if (!session.authenticated) { + window.location.href = "/login"; + return; + } + window.__KA_SESSION__ = session; + logoutCSRF.value = session.csrf_token || ""; +} + +async function loadPrinter() { + if (!printerID) { + title.textContent = "Unknown printer"; + return; + } + + const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}`, { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return; + } + if (!response.ok) { + setStatus("Not reachable", false); + agentFacts.innerHTML = fact("Agent", `Unavailable (${response.status})`); + return; + } + + const data = await response.json(); + lastData = data; + const health = data.health || {}; + const settings = data.settings || {}; + const syncState = computeSettingsSync(settings, health); + const label = (settings.display_name && String(settings.display_name).trim()) || printerID; + title.textContent = label; + + const reachable = Boolean(data.connected && health.moonraker_reachable); + setStatus(reachable ? (health.moonraker_state || "Reachable") : "Not reachable", reachable); + + agentFacts.innerHTML = [ + fact("Printer ID", printerID), + fact("Display name", settings.display_name || "Not set"), + fact("Agent hostname", health.hostname || "Unknown"), + fact("Agent version", health.agent_version || "Unknown"), + fact("Last heartbeat", health.checked_at_unix ? relativeTime(health.checked_at_unix) : "Waiting for heartbeat"), + fact("Access", data.access || "unknown"), + ].join(""); + + connectivityFacts.innerHTML = [ + fact("Connected", data.connected ? "Yes" : "No"), + fact("Moonraker", health.moonraker_reachable ? "Reachable" : "Not reachable"), + fact("Moonraker state", health.moonraker_state || "Unknown"), + fact("Moonraker message", health.moonraker_message || "No status message yet."), + fact("Moonraker URL", health.moonraker_url || "Unknown"), + fact("Camera count", String(Array.isArray(health.cameras) ? health.cameras.length : 0)), + ].join(""); + + uiFacts.innerHTML = [ + fact("Configured UI", settings.ui_url || "Auto"), + fact("Applied UI", health.ui_url || "Unavailable"), + fact("UI source", health.ui_source || "Unknown"), + fact("UI reachable", health.ui_reachable ? "Yes" : "No"), + fact("Auto-detect", settings.ui_auto_detect ? "On" : "Off"), + ].join(""); + + syncSummary.textContent = syncState.detail; + syncFacts.innerHTML = [ + fact("Control mode", settings.control_mode || "readonly"), + fact("Applied mode", health.control_mode || "Unknown"), + fact("Sync", syncState.state), + fact("Last sync", settings.last_synced_at ? new Date(settings.last_synced_at).toLocaleString() : "Unknown"), + fact("Updated", settings.updated_at ? new Date(settings.updated_at).toLocaleString() : "Unknown"), + ].join(""); + const versionState = computeVersionState(health); + renderInstallDetails(settings.install, versionState); + renderRinkhalsRuntime(settings.install, health); + renderInstallHistory(settings.install_history || [], versionState); + updateInstallAction(settings.install, versionState); + updateUpgradeButton(settings.install, versionState); + updateCheckButton(versionState); + + renderPrintStatus(data.print_status || health.print_status || null, data.print_status_error || ""); + renderRawMoonraker({ + query: (data.print_status && data.print_status.moonraker_status) || (health.print_status && health.print_status.moonraker_status) || null, + layer_source: (data.print_status && data.print_status.layer_source) || (health.print_status && health.print_status.layer_source) || "", + }, data.print_status_error || ""); + void loadRawMoonraker(); + renderCameras(health.cameras || []); + + if (uiLink) { + updateUILink(health); + } + if (installLink) { + installLink.href = installURL(settings.install); + } +} + +function updateInstallAction(install, versionState) { + if (!installAction) { + return; + } + installAction.textContent = "Reinstall via SSH"; + installAction.href = installURL(install); +} + +function installURL(install) { + const params = new URLSearchParams({ printer_id: printerID }); + const hostType = String(install && install.host_type ? install.host_type : "").trim().toLowerCase(); + if (hostType) { + params.set("host_type", hostType); + } + return `/install?${params.toString()}`; +} + +function updateUpgradeButton(install, versionState) { + if (!upgradeNow) { + return; + } + const canUpgrade = Boolean(install); + const label = !canUpgrade ? "Upgrade now" : (versionState && versionState.upToDate ? "Reinstall now" : "Upgrade now"); + upgradeNow.textContent = label; + upgradeNow.disabled = !canUpgrade; + upgradeNow.title = canUpgrade ? versionState.detail : "No saved install details are available yet."; +} + +function renderInstallDetails(install, versionState) { + if (!installFacts || !installSummary) { + return; + } + if (!install) { + installSummary.textContent = "No install details saved yet."; + if (installVersionSummary) { + installVersionSummary.textContent = versionState.detail; + } + installFacts.innerHTML = fact("Status", "None"); + return; + } + const statusLabel = String(install.status || "unknown"); + installSummary.textContent = install.error + ? `Last install failed. ${install.error}` + : install.post_install_connected + ? "Last install completed and the agent called back." + : `Last install saved for ${install.printer_id || printerID}.`; + if (installVersionSummary) { + installVersionSummary.textContent = versionState.detail; + } + installFacts.innerHTML = [ + fact("Status", statusLabel), + fact("Host", `${install.host || "Unknown"}:${install.port || 22}`), + fact("Host type", install.host_type || "standard"), + fact("Username", install.username || "Unknown"), + fact("Server URL", install.server_url || "Unknown"), + fact("Moonraker URL", install.moonraker_url || "Unknown"), + fact("UI URL", install.ui_url || "Auto"), + fact("UI auto-detect", install.ui_auto_detect ? "On" : "Off"), + fact("Requested by", install.requested_by || "Unknown"), + fact("Remote host", install.remote_host || "Unknown"), + fact("Release URL", install.release_url || "Unknown"), + fact("Binary source", install.binary_source || "Unknown"), + fact("Message", install.message || "No install message."), + fact("Post-install", install.post_install_connected ? "Confirmed" : "Pending"), + fact("Rollback", install.rollback_performed ? "Available" : "Not needed"), + fact("Updated", install.updated_at ? new Date(install.updated_at).toLocaleString() : "Unknown"), + ].join(""); +} + +function renderRinkhalsRuntime(install, health) { + if (!rinkhalsFacts || !rinkhalsSummary) { + return; + } + const isRinkhals = String(install && install.host_type ? install.host_type : "").trim().toLowerCase() === "rinkhals"; + if (!isRinkhals) { + rinkhalsSummary.textContent = "Not using the Rinkhals app runtime."; + rinkhalsFacts.innerHTML = fact("Runtime", "Not applicable"); + if (rinkhalsLink) { + rinkhalsLink.hidden = true; + } + return; + } + const enabled = Boolean(install && (install.status === "installed" || install.status === "upgraded") && install.post_install_connected); + const appRoot = String(install.binary_path || "").replace(/\/[^/]+$/, "") || "Unknown"; + rinkhalsSummary.textContent = enabled + ? "The Rinkhals app bundle is installed and has called back." + : "The Rinkhals app bundle is installed but has not confirmed a callback yet."; + rinkhalsFacts.innerHTML = [ + fact("Enabled", enabled ? "Yes" : "No"), + fact("App root", appRoot), + fact("Config path", install.config_path || "Unknown"), + fact("Launcher", "app.sh"), + fact("Status", install.status || "unknown"), + fact("Post-install", install.post_install_connected ? "Confirmed" : "Pending"), + fact("Rollback", install.rollback_performed ? "Available" : "Not needed"), + fact("Latest heartbeat", health && health.checked_at_unix ? relativeTime(health.checked_at_unix) : "Waiting for heartbeat"), + ].join(""); + if (rinkhalsLink) { + rinkhalsLink.hidden = false; + rinkhalsLink.href = `/api/printers/${encodeURIComponent(printerID)}`; + } +} + +function renderInstallHistory(history, versionState) { + if (!installHistoryList) { + return; + } + if (!Array.isArray(history) || history.length === 0) { + installHistoryList.innerHTML = '

No install history saved yet.

'; + return; + } + installHistoryList.innerHTML = history.slice(0, 8).map((entry) => { + const statusLabel = String(entry.status || "unknown"); + const statusClass = statusLabel === "installed" || statusLabel === "upgraded" ? "ok" : "warn"; + const summary = entry.error + ? `Failed: ${entry.error}` + : entry.post_install_connected + ? (statusLabel === "upgraded" ? "Agent self-update completed." : "Agent called back successfully.") + : entry.rollback_performed + ? "Replacement rolled back after reconnect timeout." + : "Install run completed."; + const context = []; + if (entry.host_type) { + context.push(entry.host_type); + } + if (entry.requested_by) { + context.push(`by ${entry.requested_by}`); + } + if (entry.binary_source) { + context.push(entry.binary_source); + } + if (entry.remote_host) { + context.push(entry.remote_host); + } + return ` +
+
+ ${escapeHTML(entry.updated_at ? new Date(entry.updated_at).toLocaleString() : "Unknown time")} + ${escapeHTML(statusLabel)} +
+

${escapeHTML(summary)}

+
+
Host
${escapeHTML(`${entry.host || "Unknown"}:${entry.port || 22}`)}
+
Username
${escapeHTML(entry.username || "Unknown")}
+
Version
${escapeHTML(entry.status === "installed" ? versionState.current : "Unknown")}
+
Context
${escapeHTML(context.join(" / ") || "No extra details")}
+
+
+ `; + }).join(""); +} + +function updateCheckButton(versionState) { + if (!updateCheck) { + return; + } + updateCheck.textContent = versionState.upToDate ? "Up to date" : "Check for updates"; + updateCheck.title = versionState.detail; + updateCheck.disabled = false; +} + +function setInstallMessage(text, ok) { + if (!installMessage) { + return; + } + if (!text) { + installMessage.hidden = true; + installMessage.textContent = ""; + installMessage.className = "form-message"; + return; + } + installMessage.hidden = false; + installMessage.textContent = text; + installMessage.className = ok ? "form-message success" : "form-message error"; +} + +async function handleUpdateCheckClick() { + if (updateCheck) { + updateCheck.disabled = true; + updateCheck.textContent = "Checking..."; + } + await loadSession(); + await loadPrinter(); +} + +async function handleUpgradeNowClick() { + if (!upgradeNow || upgradeNow.disabled) { + return; + } + upgradeNow.disabled = true; + upgradeNow.textContent = "Upgrading..."; + try { + const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}/agent/update`, { + method: "POST", + credentials: "same-origin", + headers: { + "X-CSRF-Token": logoutCSRF.value || "", + }, + }); + if (!response.ok) { + const error = await response.text(); + setInstallMessage(error || `Agent update failed (${response.status})`, false); + return; + } + const payload = await response.json().catch(() => ({})); + setInstallMessage(String(payload.reconnect_message || "Agent update requested."), true); + await loadSession(); + await loadPrinter(); + } finally { + upgradeNow.disabled = false; + } +} + +function getSSHPasswordStorageKey() { + return `ka-ssh-password:${printerID}`; +} + +function openSSHPasswordModal(targetURL) { + if (!sshPasswordModal || !sshPasswordInput || !sshPasswordContinue) { + window.location.href = targetURL; + return; + } + pendingReinstallURL = targetURL; + sshPasswordInput.value = ""; + sshPasswordModal.hidden = false; + sshPasswordInput.focus(); +} + +function closeSSHPasswordModal() { + if (!sshPasswordModal || !sshPasswordInput) { + return; + } + sshPasswordModal.hidden = true; + sshPasswordInput.value = ""; + pendingReinstallURL = ""; +} + +function confirmSSHPasswordModal() { + if (!sshPasswordInput || !pendingReinstallURL) { + return; + } + const password = String(sshPasswordInput.value || "").trim(); + if (!password) { + setInstallMessage("SSH password is required to continue with reinstall.", false); + return; + } + try { + sessionStorage.setItem(getSSHPasswordStorageKey(), password); + } catch { + // Session storage can fail in private/locked-down modes; continue anyway. + } + const targetURL = pendingReinstallURL; + closeSSHPasswordModal(); + window.location.href = targetURL; +} + +function renderPrintStatus(statusData, error) { + if (!printStatusFacts) { + return; + } + if (!statusData) { + printStatusFacts.innerHTML = fact("State", error ? `Unavailable (${error})` : "Unknown"); + return; + } + const printStats = statusData.print_stats || statusData; + const displayStatus = statusData.display_status || statusData; + printStatusFacts.innerHTML = [ + fact("State", printStats.state || "Unknown"), + fact("File", printStats.filename || "No file loaded"), + fact("Progress", formatProgress(displayStatus.progress)), + fact("Print duration", formatDuration(printStats.print_duration)), + fact("Total duration", formatDuration(printStats.total_duration)), + fact("Remaining", formatDuration(printStats.estimated_time_remaining || printStats.estimated_duration)), + fact("Filament", formatFilament(printStats.filament_used)), + fact("Message", printStats.message || displayStatus.message || "No status message yet."), + ].join(""); +} + +function renderRawMoonraker(payload, error) { + if (!moonrakerRawFacts || !moonrakerRawSummary || !moonrakerRawJson) { + return; + } + const rawQuery = payload && typeof payload === "object" && payload.query && typeof payload.query === "object" ? payload.query : null; + const layerSource = payload && typeof payload === "object" && typeof payload.layer_source === "string" ? payload.layer_source : ""; + const rawStatus = rawQuery; + if (!rawStatus) { + moonrakerRawSummary.textContent = error ? `Raw Moonraker payload unavailable (${error}).` : "Raw Moonraker payload unavailable."; + moonrakerRawFacts.innerHTML = [ + fact("Raw keys", "None"), + fact("MMU keys", "None"), + fact("print_stats.info.current_layer", "Unset"), + fact("print_stats.info.total_layer", "Unset"), + fact("Layer source", layerSource || "Unset"), + fact("display_status.progress", "0%"), + fact("gcode_move.position.z", "Unset"), + fact("toolhead.position.z", "Unset"), + fact("mmu.enabled", "Unset"), + fact("mmu.print_state", "Unset"), + fact("mmu.action", "Unset"), + fact("mmu_machine.unit_0.name", "Unset"), + fact("display_status.message", "No raw payload available."), + ].join(""); + moonrakerRawJson.textContent = "Waiting for raw Moonraker data..."; + return; + } + + const printStats = rawStatus.print_stats || {}; + const displayStatus = rawStatus.display_status || {}; + const gcodeMove = rawStatus.gcode_move || {}; + const toolhead = rawStatus.toolhead || {}; + const mmu = rawStatus.mmu && typeof rawStatus.mmu === "object" ? rawStatus.mmu : null; + const mmuMachine = rawStatus.mmu_machine && typeof rawStatus.mmu_machine === "object" ? rawStatus.mmu_machine : null; + const printInfo = printStats.info || {}; + const currentLayer = printInfo.current_layer ?? printStats.current_layer ?? displayStatus.current_layer ?? null; + const totalLayer = printInfo.total_layer ?? printStats.total_layer ?? displayStatus.total_layer ?? null; + const rawKeys = Object.keys(rawStatus).sort().join(", ") || "None"; + const mmuKeys = mmu && typeof mmu === "object" ? Object.keys(mmu).sort().join(", ") || "None" : "None"; + const mmuMachineName = mmuMachine && mmuMachine.unit_0 && typeof mmuMachine.unit_0 === "object" && mmuMachine.unit_0.name ? String(mmuMachine.unit_0.name) : "Unset"; + const mmuEnabled = mmu && Object.prototype.hasOwnProperty.call(mmu, "enabled") + ? (mmu.enabled ? "Yes" : "No") + : "Unset"; + const activeFilament = mmu && mmu.active_filament && typeof mmu.active_filament === "object" + ? [ + mmu.active_filament.vendor || "", + mmu.active_filament.manufacturer || "", + mmu.active_filament.material || "", + mmu.active_filament.color || "", + ].filter((value) => String(value || "").trim()).join(" / ") || "Unset" + : "Unset"; + + moonrakerRawSummary.textContent = "Raw Moonraker query payload from the agent heartbeat."; + moonrakerRawFacts.innerHTML = [ + fact("Raw keys", rawKeys), + fact("MMU keys", mmuKeys), + fact("print_stats.info.current_layer", currentLayer === null || currentLayer === undefined ? "Unset" : String(currentLayer)), + fact("print_stats.info.total_layer", totalLayer === null || totalLayer === undefined ? "Unset" : String(totalLayer)), + fact("Layer source", layerSource || "Unset"), + fact("display_status.progress", formatProgress(displayStatus.progress)), + fact("display_status.message", displayStatus.message || "No message"), + fact("gcode_move.position.z", formatDecimal(positionZ(gcodeMove))), + fact("toolhead.position.z", formatDecimal(positionZ(toolhead))), + fact("mmu.enabled", mmuEnabled), + fact("mmu.print_state", mmu && mmu.print_state ? String(mmu.print_state) : "Unset"), + fact("mmu.action", mmu && mmu.action ? String(mmu.action) : "Unset"), + fact("mmu_machine.unit_0.name", mmuMachineName), + fact("mmu.active_filament", activeFilament), + ].join(""); + moonrakerRawJson.textContent = JSON.stringify({ query: rawStatus }, null, 2); +} + +async function loadRawMoonraker() { + if (!moonrakerRawFacts || !moonrakerRawSummary || !moonrakerRawJson) { + return; + } + if (!printerID) { + return; + } + try { + const response = await fetch(`/p/${encodeURIComponent(printerID)}/moonraker/printer/objects/query?print_stats&display_status&gcode_move&toolhead`, { + credentials: "same-origin", + }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}`); + } + const payload = await response.json(); + const rawStatus = payload && payload.result && payload.result.status ? payload.result.status : null; + renderRawMoonraker({ + query: rawStatus, + layer_source: (lastData && ((lastData.print_status && lastData.print_status.layer_source) || (lastData.health && lastData.health.print_status && lastData.health.print_status.layer_source))) || "", + }, ""); + } catch (error) { + const fallbackQuery = lastData && ((lastData.print_status && lastData.print_status.moonraker_status) || (lastData.health && lastData.health.print_status && lastData.health.print_status.moonraker_status)) || null; + const fallbackLayerSource = lastData && ((lastData.print_status && lastData.print_status.layer_source) || (lastData.health && lastData.health.print_status && lastData.health.print_status.layer_source)) || ""; + renderRawMoonraker({ query: fallbackQuery, layer_source: fallbackLayerSource }, error && error.message ? error.message : String(error || "unknown error")); + } +} + +function positionZ(source) { + if (!source || typeof source !== "object") { + return null; + } + for (const key of ["position", "gcode_position"]) { + const value = source[key]; + if (Array.isArray(value) && value.length > 2) { + const number = Number(value[2]); + if (Number.isFinite(number)) { + return number; + } + } + } + return null; +} + +function formatDecimal(value) { + if (value === null || value === undefined || value === "") { + return "Unset"; + } + const number = Number(value); + if (!Number.isFinite(number)) { + return "Unset"; + } + return number.toFixed(3).replace(/\.?0+$/, ""); +} + +function renderCameras(cameras) { + if (!cameraList) { + return; + } + if (!Array.isArray(cameras) || cameras.length === 0) { + cameraList.innerHTML = '

No cameras are configured for this agent.

'; + return; + } + cameraList.innerHTML = cameras.map((camera) => { + const previewBits = []; + if (camera.location) { + previewBits.push(camera.location); + } + if (camera.service) { + previewBits.push(camera.service); + } + if (camera.source) { + previewBits.push(camera.source); + } + const snapshotURL = `/p/${encodeURIComponent(printerID)}/camera/${encodeURIComponent(camera.name)}/snapshot`; + const streamURL = `/p/${encodeURIComponent(printerID)}/camera/${encodeURIComponent(camera.name)}/stream`; + return ` +
+
+ ${escapeHTML(camera.name || "Camera")} + ${camera.has_stream ? "stream" : "snapshot"} +
+
+
Source
${escapeHTML(previewBits.join(" / ") || "Configured camera")}
+
Snapshot
${camera.has_snapshot ? `Open` : "Unavailable"}
+
Stream
${camera.has_stream ? `Open` : "Unavailable"}
+
Aspect
${escapeHTML(camera.aspect_ratio || "16:9")}
+
+
+ `; + }).join(""); +} + +function updateUILink(health) { + if (!uiLink) { + return; + } + const uiRoute = `/printers/${encodeURIComponent(printerID)}/ui/`; + if (health.ui_reachable) { + uiLink.href = uiRoute; + uiLink.removeAttribute("aria-disabled"); + uiLink.classList.remove("disabled"); + uiLink.textContent = "Open Printer UI"; + return; + } + uiLink.href = "#"; + uiLink.setAttribute("aria-disabled", "true"); + uiLink.classList.add("disabled"); + uiLink.textContent = "UI unavailable"; +} + +function computeSettingsSync(settings, health) { + const updatedAt = parseTimestamp(settings.updated_at); + const lastSyncedAt = parseTimestamp(settings.last_synced_at); + const controlMode = String(settings.control_mode || "").toLowerCase() || "readonly"; + const appliedMode = String(health.control_mode || "").toLowerCase() || "unknown"; + const uiURL = String(settings.ui_url || "").trim(); + const agentUIURL = String(health.ui_url || "").trim(); + const autoDetect = Boolean(settings.ui_auto_detect); + const agentAutoDetect = Boolean(health.ui_auto_detect); + const synced = Boolean(updatedAt && lastSyncedAt && lastSyncedAt >= updatedAt); + if (synced) { + return { + synced: true, + state: "Synced", + detail: "Agent acknowledged the latest saved settings.", + }; + } + const detailBits = []; + if (controlMode !== appliedMode && appliedMode !== "unknown") { + detailBits.push(`control mode ${controlMode} -> ${appliedMode}`); + } + if (uiURL && uiURL !== agentUIURL) { + detailBits.push(`UI URL ${uiURL} -> ${agentUIURL || "unset"}`); + } + if (autoDetect !== agentAutoDetect) { + detailBits.push(`auto-detect ${autoDetect} -> ${agentAutoDetect}`); + } + return { + synced: false, + state: "Pending", + detail: detailBits.length > 0 ? `Waiting for agent confirmation; ${detailBits.join("; ")}` : "Waiting for the agent to confirm the latest settings.", + }; +} + +function computeVersionState(health) { + const current = String(health && health.agent_version ? health.agent_version : "Unknown"); + const available = String(window.__KA_SESSION__ && window.__KA_SESSION__.server_version ? window.__KA_SESSION__.server_version : "dev"); + const upToDate = Boolean(current && available && current !== "Unknown" && available !== "Unknown" && current === available); + return { + current, + available, + upToDate, + detail: upToDate + ? `Agent ${current} is up to date.` + : current === "Unknown" + ? `Available agent version: ${available}.` + : `Installed agent ${current}; available ${available}.`, + }; +} + +function setStatus(label, ok) { + status.textContent = label; + status.classList.toggle("ok", ok); + status.classList.toggle("warn", !ok); +} + +function fact(label, value) { + return `
${escapeHTML(label)}
${escapeHTML(value)}
`; +} + +function parseTimestamp(value) { + if (!value) { + return 0; + } + const parsed = Date.parse(value); + return Number.isFinite(parsed) ? parsed : 0; +} + +function relativeTime(unixSeconds) { + const seconds = Math.max(0, Math.floor(Date.now() / 1000) - unixSeconds); + if (seconds < 5) { + return "just now"; + } + if (seconds < 60) { + return `${seconds}s ago`; + } + const minutes = Math.floor(seconds / 60); + if (minutes < 60) { + return `${minutes}m ago`; + } + const hours = Math.floor(minutes / 60); + return `${hours}h ago`; +} + +function formatProgress(value) { + const progress = Number(value); + if (!Number.isFinite(progress) || progress <= 0) { + return "0%"; + } + if (progress <= 1) { + return `${Math.round(progress * 100)}%`; + } + return `${Math.round(progress)}%`; +} + +function formatDuration(value) { + const seconds = Number(value); + if (!Number.isFinite(seconds) || seconds < 0) { + return "Unknown"; + } + const whole = Math.floor(seconds); + const hours = Math.floor(whole / 3600); + const minutes = Math.floor((whole % 3600) / 60); + const secs = whole % 60; + if (hours > 0) { + return `${hours}h ${minutes}m ${secs}s`; + } + if (minutes > 0) { + return `${minutes}m ${secs}s`; + } + return `${secs}s`; +} + +function formatFilament(value) { + const number = Number(value); + if (!Number.isFinite(number) || number <= 0) { + return "Unknown"; + } + return `${number.toFixed(1)} mm`; +} + +function escapeHTML(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +refresh.addEventListener("click", loadPrinter); +if (updateCheck) { + updateCheck.addEventListener("click", handleUpdateCheckClick); +} +if (upgradeNow) { + upgradeNow.addEventListener("click", handleUpgradeNowClick); +} +if (installAction) { + installAction.addEventListener("click", (event) => { + event.preventDefault(); + openSSHPasswordModal(installAction.href); + }); +} +if (sshPasswordCancel) { + sshPasswordCancel.addEventListener("click", () => closeSSHPasswordModal()); +} +if (sshPasswordContinue) { + sshPasswordContinue.addEventListener("click", () => confirmSSHPasswordModal()); +} +if (sshPasswordModal) { + sshPasswordModal.addEventListener("click", (event) => { + if (event.target === sshPasswordModal) { + closeSSHPasswordModal(); + } + }); +} +loadSession().then(loadPrinter); +setInterval(loadPrinter, 15000); diff --git a/web/static/printer-settings.html b/web/static/printer-settings.html new file mode 100644 index 0000000..589baa8 --- /dev/null +++ b/web/static/printer-settings.html @@ -0,0 +1,165 @@ + + + + + + Printer Settings - KlipperAnywhere + + + + + + + +
+ + + KlipperAnywhere + + +
+ +
+
+
+

Printer settings

+

Loading...

+
+ Checking +
+ +
+
+
+

Identity

+ Open +
+
+
Printer
Loading...
+
+
+ +
+
+
+

Editable settings

+

Waiting for printer heartbeat.

+
+ Pending +
+

Rename the printer for the UI and keep the agent sync settings in one place.

+ +
+ + + + + +
+ +
+
+
+

Print notifications

+

No notification types configured yet.

+
+
+ Off +
+
+
+ +
+ + + + + + +
+
+ + +
+ +

These toggles control which print events this printer emits. Telegram delivery is configured globally from Admin.

+ +
+
+ +
+
+
+

Agent applied

+

Waiting for printer heartbeat.

+
+
+ Pending + Upgrade agent +
+
+
+
Applied mode
Waiting...
+
Applied UI URL
Waiting...
+
UI source
Waiting...
+
UI reachable
Waiting...
+
Moonraker
Waiting...
+
Last heartbeat
Waiting...
+
Current agent
Waiting...
+
Available agent
Waiting...
+
+
+
+
+
+ + + + + + diff --git a/web/static/printer-settings.js b/web/static/printer-settings.js new file mode 100644 index 0000000..a429cc6 --- /dev/null +++ b/web/static/printer-settings.js @@ -0,0 +1,435 @@ +const refresh = document.getElementById("refresh"); +const title = document.getElementById("printer-title"); +const status = document.getElementById("printer-status"); +const identityFacts = document.getElementById("identity-facts"); +const settingsSummary = document.getElementById("settings-summary"); +const settingsSyncPill = document.getElementById("settings-sync-pill"); +const settingsMessage = document.getElementById("settings-message"); +const settingsForm = document.getElementById("printer-settings-form"); +const settingsDisplayName = document.getElementById("settings-display-name"); +const settingsControlMode = document.getElementById("settings-control-mode"); +const settingsUIURL = document.getElementById("settings-ui-url"); +const settingsUIAutoDetect = document.getElementById("settings-ui-auto-detect"); +const notificationsSummary = document.getElementById("notifications-summary"); +const notificationsPill = document.getElementById("notifications-pill"); +const notificationsForm = document.getElementById("printer-notifications-form"); +const settingsNotificationsEnabled = document.getElementById("settings-notifications-enabled"); +const settingsNotifyStarted = document.getElementById("settings-notify-started"); +const settingsNotifyPaused = document.getElementById("settings-notify-paused"); +const settingsNotifyResumed = document.getElementById("settings-notify-resumed"); +const settingsNotifyCompleted = document.getElementById("settings-notify-completed"); +const settingsNotifyCanceled = document.getElementById("settings-notify-canceled"); +const settingsNotifyFailed = document.getElementById("settings-notify-failed"); +const settingsNotifyFirstLayer = document.getElementById("settings-notify-first-layer"); +const settingsNotifyThirdLayer = document.getElementById("settings-notify-third-layer"); +const settingsNotificationSnapshotCamera = document.getElementById("settings-notification-snapshot-camera"); +const settingsAppliedSummary = document.getElementById("settings-applied-summary"); +const settingsAppliedPill = document.getElementById("settings-applied-pill"); +const settingsAppliedFacts = document.getElementById("settings-applied-facts"); +const settingsUpgradeLink = document.getElementById("settings-upgrade-link"); +const logoutCSRF = document.getElementById("logout-csrf"); +const backLink = document.getElementById("back-link"); +const agentLink = document.getElementById("agent-link"); +const uiLink = document.getElementById("ui-link"); +const printerOpenLink = document.getElementById("printer-open-link"); +const adminLink = document.getElementById("admin-link"); + +const printerID = decodeURIComponent(window.location.pathname.replace(/^\/printers\//, "").replace(/\/settings\/?$/, "")); +let settingsDirty = false; +let lastHealth = null; + +if (printerID) { + backLink.href = `/printers/${encodeURIComponent(printerID)}`; + printerOpenLink.href = `/printers/${encodeURIComponent(printerID)}`; + if (agentLink) { + agentLink.href = `/printers/${encodeURIComponent(printerID)}/agent`; + } + uiLink.href = `/printers/${encodeURIComponent(printerID)}/ui/`; + if (settingsUpgradeLink) { + settingsUpgradeLink.href = `/install?printer_id=${encodeURIComponent(printerID)}`; + } + if (adminLink) { + adminLink.href = `/admin?printer_id=${encodeURIComponent(printerID)}`; + } +} + +async function loadSession() { + const response = await fetch("/api/session", { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return; + } + const session = await response.json(); + if (!session.authenticated) { + window.location.href = "/login"; + return; + } + window.__KA_SESSION__ = session; + logoutCSRF.value = session.csrf_token || ""; +} + +async function loadPrinter() { + if (!printerID) { + title.textContent = "Unknown printer"; + return; + } + + const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}`, { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return; + } + if (!response.ok) { + identityFacts.innerHTML = fact("Printer", `Unavailable (${response.status})`); + setStatus("Not reachable", false); + return; + } + const data = await response.json(); + const health = data.health || {}; + const settings = data.settings || {}; + const label = settings.display_name || printerID; + lastHealth = health; + + title.textContent = label; + setStatus(data.connected && health.moonraker_reachable ? "Reachable" : "Not reachable", data.connected && health.moonraker_reachable); + identityFacts.innerHTML = [ + fact("Printer ID", printerID), + fact("Display name", settings.display_name || "Not set"), + fact("Agent hostname", health.hostname || "Unknown"), + fact("Agent version", health.agent_version || "Unknown"), + fact("Moonraker", health.moonraker_state || "Unknown"), + fact("UI source", health.ui_source || "Unknown"), + ].join(""); + + if (settingsDirty) { + return; + } + settingsDisplayName.value = settings.display_name || ""; + settingsControlMode.value = settings.control_mode || "readonly"; + settingsUIURL.value = settings.ui_url || ""; + settingsUIAutoDetect.checked = Boolean(settings.ui_auto_detect); + if (settingsNotificationsEnabled) { + settingsNotificationsEnabled.checked = Boolean(settings.print_notifications_enabled); + } + if (settingsNotifyStarted) { + settingsNotifyStarted.checked = Boolean(settings.notify_print_started); + } + if (settingsNotifyPaused) { + settingsNotifyPaused.checked = Boolean(settings.notify_print_paused); + } + if (settingsNotifyResumed) { + settingsNotifyResumed.checked = Boolean(settings.notify_print_resumed); + } + if (settingsNotifyCompleted) { + settingsNotifyCompleted.checked = Boolean(settings.notify_print_completed); + } + if (settingsNotifyCanceled) { + settingsNotifyCanceled.checked = Boolean(settings.notify_print_canceled); + } + if (settingsNotifyFailed) { + settingsNotifyFailed.checked = Boolean(settings.notify_print_failed); + } + if (settingsNotifyFirstLayer) { + settingsNotifyFirstLayer.checked = Boolean(settings.notify_print_first_layer); + } + if (settingsNotifyThirdLayer) { + settingsNotifyThirdLayer.checked = Boolean(settings.notify_print_third_layer); + } + renderSnapshotCameraOptions(health.cameras || [], settings.notification_snapshot_camera || ""); + renderNotificationState(settings); + if (settingsSyncPill) { + const syncState = computeSettingsSync(settings, health); + settingsSyncPill.textContent = syncState.state; + settingsSyncPill.classList.toggle("ok", syncState.synced); + settingsSyncPill.classList.toggle("warn", !syncState.synced); + if (settingsSummary) { + settingsSummary.textContent = syncState.detail; + } + } + renderAppliedState(data.settings_synced, data.settings_sync_state, data.settings_sync_detail, health); + if (settingsUpgradeLink) { + settingsUpgradeLink.href = installURL(settings.install); + } +} + +async function saveSettings(event) { + event.preventDefault(); + setSettingsMessage("Saving settings...", true); + const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}/settings`, { + method: "PATCH", + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": logoutCSRF.value || "", + }, + body: JSON.stringify({ + display_name: settingsDisplayName.value, + control_mode: settingsControlMode.value, + ui_url: settingsUIURL.value, + ui_auto_detect: settingsUIAutoDetect.checked, + }), + }); + if (!response.ok) { + const error = await response.text(); + setSettingsMessage(error || `Failed to save settings (${response.status})`, false); + return; + } + const payload = await response.json().catch(() => ({})); + settingsDirty = false; + const syncState = String(payload.settings_sync_state || (payload.settings_synced ? "Synced" : "Pending")); + const syncDetail = String(payload.settings_sync_detail || "").trim(); + setSettingsMessage(syncDetail ? `Saved. ${syncDetail}` : `Saved. ${syncState}.`, true); + renderAppliedState(payload.settings_synced, payload.settings_sync_state, payload.settings_sync_detail, lastHealth); + if (settingsUpgradeLink) { + settingsUpgradeLink.href = installURL(payload.install || null); + } + await loadPrinter(); +} + +async function saveNotifications(event) { + event.preventDefault(); + setSettingsMessage("Saving notification settings...", true); + const payload = { + print_notifications_enabled: Boolean(settingsNotificationsEnabled && settingsNotificationsEnabled.checked), + notify_print_started: Boolean(settingsNotifyStarted && settingsNotifyStarted.checked), + notify_print_paused: Boolean(settingsNotifyPaused && settingsNotifyPaused.checked), + notify_print_resumed: Boolean(settingsNotifyResumed && settingsNotifyResumed.checked), + notify_print_completed: Boolean(settingsNotifyCompleted && settingsNotifyCompleted.checked), + notify_print_canceled: Boolean(settingsNotifyCanceled && settingsNotifyCanceled.checked), + notify_print_failed: Boolean(settingsNotifyFailed && settingsNotifyFailed.checked), + notify_print_first_layer: Boolean(settingsNotifyFirstLayer && settingsNotifyFirstLayer.checked), + notify_print_third_layer: Boolean(settingsNotifyThirdLayer && settingsNotifyThirdLayer.checked), + notification_snapshot_camera: settingsNotificationSnapshotCamera ? settingsNotificationSnapshotCamera.value : "", + }; + const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}/settings`, { + method: "PATCH", + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": logoutCSRF.value || "", + }, + body: JSON.stringify(payload), + }); + if (!response.ok) { + const error = await response.text(); + setSettingsMessage(error || `Failed to save notification settings (${response.status})`, false); + return; + } + const payloadResponse = await response.json().catch(() => ({})); + settingsDirty = false; + const syncState = String(payloadResponse.settings_sync_state || (payloadResponse.settings_synced ? "Synced" : "Pending")); + const syncDetail = String(payloadResponse.settings_sync_detail || "").trim(); + setSettingsMessage(syncDetail ? `Notification settings saved. ${syncDetail}` : `Notification settings saved. ${syncState}.`, true); + renderAppliedState(payloadResponse.settings_synced, payloadResponse.settings_sync_state, payloadResponse.settings_sync_detail, lastHealth); + if (settingsUpgradeLink) { + settingsUpgradeLink.href = installURL(payloadResponse.install || null); + } + await loadPrinter(); +} + +function installURL(install) { + const params = new URLSearchParams({ printer_id: printerID }); + const hostType = String(install && install.host_type ? install.host_type : "").trim().toLowerCase(); + if (hostType) { + params.set("host_type", hostType); + } + return `/install?${params.toString()}`; +} + +function computeSettingsSync(settings, health) { + const updatedAt = parseTimestamp(settings.updated_at); + const lastSyncedAt = parseTimestamp(settings.last_synced_at); + const controlMode = String(settings.control_mode || "").toLowerCase() || "readonly"; + const appliedMode = String(health.control_mode || "").toLowerCase() || "unknown"; + const uiURL = String(settings.ui_url || "").trim(); + const agentUIURL = String(health.ui_url || "").trim(); + const autoDetect = Boolean(settings.ui_auto_detect); + const agentAutoDetect = Boolean(health.ui_auto_detect); + const synced = Boolean(updatedAt && lastSyncedAt && lastSyncedAt >= updatedAt); + if (synced) { + return { + synced: true, + state: "Synced", + detail: "Agent acknowledged the latest synced settings.", + }; + } + const detailBits = []; + if (controlMode !== appliedMode && appliedMode !== "unknown") { + detailBits.push(`control mode ${controlMode} -> ${appliedMode}`); + } + if (uiURL && uiURL !== agentUIURL) { + detailBits.push(`UI URL ${uiURL} -> ${agentUIURL || "unset"}`); + } + if (autoDetect !== agentAutoDetect) { + detailBits.push(`auto-detect ${autoDetect} -> ${agentAutoDetect}`); + } + return { + synced: false, + state: "Pending", + detail: detailBits.length > 0 ? `Waiting for agent confirmation; ${detailBits.join("; ")}` : "Waiting for the agent to confirm the latest settings.", + }; +} + +function setStatus(label, ok) { + status.textContent = label; + status.classList.toggle("ok", ok); + status.classList.toggle("warn", !ok); +} + +function setSettingsMessage(text, ok) { + if (!settingsMessage) { + return; + } + if (!text) { + settingsMessage.hidden = true; + settingsMessage.textContent = ""; + settingsMessage.className = "form-message"; + return; + } + settingsMessage.hidden = false; + settingsMessage.textContent = text; + settingsMessage.className = ok ? "form-message success" : "form-message error"; +} + +function renderAppliedState(settingsSynced, settingsSyncState, settingsSyncDetail, health) { + if (!settingsAppliedPill || !settingsAppliedSummary || !settingsAppliedFacts) { + return; + } + const synced = Boolean(settingsSynced); + const state = String(settingsSyncState || (synced ? "Synced" : "Pending")); + settingsAppliedPill.textContent = state; + settingsAppliedPill.classList.toggle("ok", synced); + settingsAppliedPill.classList.toggle("warn", !synced); + settingsAppliedSummary.textContent = String(settingsSyncDetail || (synced ? "Agent acknowledged the latest saved settings." : "Waiting for the agent to confirm the latest settings.")); + const sessionVersion = String(window.__KA_SESSION__ && window.__KA_SESSION__.server_version ? window.__KA_SESSION__.server_version : "dev"); + + const appliedMode = String(health && health.control_mode ? health.control_mode : "Unknown"); + const appliedURL = String(health && health.ui_url ? health.ui_url : "Unset"); + const uiSource = String(health && health.ui_source ? health.ui_source : "Unknown"); + const uiReachable = health ? (health.ui_reachable ? "Yes" : "No") : "Unknown"; + const moonraker = String(health && health.moonraker_state ? health.moonraker_state : "Unknown"); + const heartbeat = health && health.checked_at_unix ? new Date(health.checked_at_unix * 1000).toLocaleString() : "Unknown"; + const currentVersion = String(health && health.agent_version ? health.agent_version : "Unknown"); + const upgradeAvailable = currentVersion !== "Unknown" && sessionVersion !== "Unknown" && currentVersion !== sessionVersion; + if (settingsUpgradeLink && printerID) { + settingsUpgradeLink.href = `/install?printer_id=${encodeURIComponent(printerID)}`; + settingsUpgradeLink.textContent = upgradeAvailable ? "Upgrade agent" : "Reinstall agent"; + } + settingsAppliedFacts.innerHTML = [ + fact("Applied mode", appliedMode), + fact("Applied UI URL", appliedURL), + fact("UI source", uiSource), + fact("UI reachable", uiReachable), + fact("Moonraker", moonraker), + fact("Last heartbeat", heartbeat), + fact("Current agent", currentVersion), + fact("Available agent", sessionVersion), + ].join(""); +} + +function renderNotificationState(settings) { + if (!notificationsPill || !notificationsSummary) { + return; + } + const enabled = Boolean(settings && settings.print_notifications_enabled); + const deliveryReady = Boolean(settings && settings.notification_delivery_ready); + const deliverySource = String(settings && settings.notification_delivery_source ? settings.notification_delivery_source : ""); + const lastError = String(settings && settings.last_notification_error ? settings.last_notification_error : "").trim(); + const snapshotCamera = String(settings && settings.notification_snapshot_camera ? settings.notification_snapshot_camera : "").trim(); + const selected = []; + if (settings && settings.notify_print_started) selected.push("started"); + if (settings && settings.notify_print_paused) selected.push("paused"); + if (settings && settings.notify_print_resumed) selected.push("resumed"); + if (settings && settings.notify_print_completed) selected.push("completed"); + if (settings && settings.notify_print_canceled) selected.push("canceled"); + if (settings && settings.notify_print_failed) selected.push("failed"); + if (settings && settings.notify_print_first_layer) selected.push("first layer"); + if (settings && settings.notify_print_third_layer) selected.push("third layer"); + const ready = enabled && selected.length > 0; + notificationsPill.textContent = ready ? "On" : "Off"; + notificationsPill.classList.toggle("ok", ready); + notificationsPill.classList.toggle("warn", !ready); + if (!enabled) { + notificationsSummary.textContent = "Print notifications are disabled for this printer."; + } else if (selected.length === 0) { + notificationsSummary.textContent = "Enable at least one notification type for this printer."; + } else if (!deliveryReady) { + notificationsSummary.textContent = "Notification types are enabled for this printer, but Telegram delivery is not configured in Admin yet."; + } else if (lastError) { + notificationsSummary.textContent = `Print notifications are enabled. Last send failed: ${lastError}`; + } else { + const cameraText = snapshotCamera ? ` Snapshot camera: ${snapshotCamera}.` : ""; + notificationsSummary.textContent = `Print notifications are enabled for ${selected.join(", ")}. Telegram delivery is configured in Admin${deliverySource ? ` (${deliverySource})` : ""}.${cameraText}`; + } +} + +function renderSnapshotCameraOptions(cameras, selectedCamera) { + if (!settingsNotificationSnapshotCamera) { + return; + } + const snapshotCameras = Array.isArray(cameras) ? cameras.filter((camera) => camera && camera.has_snapshot && String(camera.name || "").trim() !== "") : []; + const selected = String(selectedCamera || "").trim(); + const options = ['']; + let hasSelected = selected === ""; + snapshotCameras.forEach((camera) => { + const name = String(camera.name || "").trim(); + if (name === selected) { + hasSelected = true; + } + options.push(``); + }); + if (selected && !hasSelected) { + options.push(``); + } + settingsNotificationSnapshotCamera.innerHTML = options.join(""); + settingsNotificationSnapshotCamera.value = selected; + settingsNotificationSnapshotCamera.disabled = snapshotCameras.length === 0 && selected === ""; +} + +function fact(label, value) { + return `
${escapeHTML(label)}
${escapeHTML(value)}
`; +} + +function parseTimestamp(value) { + if (!value) { + return 0; + } + const parsed = Date.parse(value); + return Number.isFinite(parsed) ? parsed : 0; +} + +function escapeHTML(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +refresh.addEventListener("click", loadPrinter); +if (settingsForm) { + settingsForm.addEventListener("submit", saveSettings); + settingsForm.addEventListener("input", () => { + settingsDirty = true; + }); + settingsForm.addEventListener("change", () => { + settingsDirty = true; + }); +} +if (notificationsForm) { + notificationsForm.addEventListener("submit", saveNotifications); + notificationsForm.addEventListener("input", () => { + settingsDirty = true; + }); + notificationsForm.addEventListener("change", () => { + settingsDirty = true; + }); +} + +if (settingsNotificationSnapshotCamera) { + settingsNotificationSnapshotCamera.addEventListener("change", () => { + settingsDirty = true; + }); +} +loadSession().then(loadPrinter); diff --git a/web/static/printer-switcher.js b/web/static/printer-switcher.js new file mode 100644 index 0000000..c709b6e --- /dev/null +++ b/web/static/printer-switcher.js @@ -0,0 +1,105 @@ +(() => { + const select = document.getElementById("printer-switcher"); + const openButton = document.getElementById("printer-switcher-open"); + if (!select || !openButton) { + return; + } + + const session = window.__KA_SESSION__ || {}; + const currentPath = window.location.pathname || "/"; + const currentQuery = new URLSearchParams(window.location.search || ""); + + function currentPrinterID() { + const printerPath = currentPath.match(/^\/printers\/([^/]+)/); + if (printerPath && printerPath[1]) { + return decodeURIComponent(printerPath[1]); + } + const queryPrinterID = (currentQuery.get("printer_id") || "").trim(); + if (queryPrinterID) { + return queryPrinterID; + } + const queryPrinter = (currentQuery.get("printer") || "").trim(); + if (queryPrinter) { + return queryPrinter; + } + return ""; + } + + function targetForPrinter(printerID) { + const encoded = encodeURIComponent(printerID); + if (currentPath === "/dashboard" || currentPath === "/" || currentPath === "/admin" || currentPath === "/account" || currentPath === "/users" || currentPath === "/audit" || currentPath === "/install") { + return `/printers/${encoded}`; + } + if (/^\/printers\/[^/]+\/settings\/?$/.test(currentPath)) { + return `/printers/${encoded}/settings`; + } + if (/^\/printers\/[^/]+\/agent\/?$/.test(currentPath)) { + return `/printers/${encoded}/agent`; + } + if (/^\/printers\/[^/]+\/ui\/?/.test(currentPath)) { + return `/printers/${encoded}/ui/`; + } + if (/^\/printers\/[^/]+$/.test(currentPath)) { + return `/printers/${encoded}`; + } + return `/printers/${encoded}`; + } + + function openSelectedPrinter() { + const printerID = select.value.trim(); + if (!printerID) { + return; + } + window.location.assign(targetForPrinter(printerID)); + } + + async function loadPrinters() { + const response = await fetch("/api/printers", { credentials: "same-origin" }); + if (!response.ok) { + select.innerHTML = ''; + select.disabled = true; + openButton.disabled = true; + return; + } + const payload = await response.json(); + const printers = Array.isArray(payload.printers) ? payload.printers : []; + if (!printers.length) { + select.innerHTML = ''; + select.disabled = true; + openButton.disabled = true; + return; + } + const activePrinter = currentPrinterID(); + select.innerHTML = printers.map((printer) => { + const printerID = String(printer.printer_id || ""); + const settings = printer.settings || {}; + const label = String(settings.display_name || printerID || "Printer"); + const selected = printerID === activePrinter ? " selected" : ""; + return ``; + }).join(""); + if (activePrinter && printers.some((printer) => String(printer.printer_id || "") === activePrinter)) { + select.value = activePrinter; + } + select.disabled = false; + openButton.disabled = !select.value; + } + + function escapeHTML(value) { + return String(value || "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); + } + + select.addEventListener("change", () => { + openButton.disabled = !select.value; + }); + openButton.addEventListener("click", openSelectedPrinter); + + loadPrinters().catch(() => { + select.innerHTML = ''; + select.disabled = true; + openButton.disabled = true; + }); +})(); diff --git a/web/static/printer.html b/web/static/printer.html new file mode 100644 index 0000000..2872912 --- /dev/null +++ b/web/static/printer.html @@ -0,0 +1,151 @@ + + + + + + Printer - KlipperAnywhere + + + + + + + +
+ + + KlipperAnywhere + + +
+ +
+
+
+

Printer

+

Loading...

+
+ Checking +
+ +
+
+
+

Connection

+ JSON +
+
+
Agent
Loading...
+
+
+ +
+
+

Moonraker Info

+ Raw +
+
+
Printer
Loading...
+
+
+ +
+
+

Print Status

+ Raw +
+ + + + +
+ +
+
+

Temperatures

+
+
+
Temps
Loading...
+
+
+ +
+
+

Recent Jobs

+ Raw +
+
+

Loading recent jobs...

+
+
+ +
+
+

Cameras

+
+
+

Waiting for camera configuration...

+
+
+ +
+
+

Printer UI

+ Open +
+
+
UI
Loading...
+
+
+ + +
+
+ + + + + + diff --git a/web/static/printer.js b/web/static/printer.js new file mode 100644 index 0000000..f58acf8 --- /dev/null +++ b/web/static/printer.js @@ -0,0 +1,1140 @@ +const refresh = document.getElementById("refresh"); +const title = document.getElementById("printer-title"); +const status = document.getElementById("printer-status"); +const healthFacts = document.getElementById("health-facts"); +const infoFacts = document.getElementById("info-facts"); +const cameraList = document.getElementById("camera-list"); +const healthLink = document.getElementById("health-link"); +const infoLink = document.getElementById("info-link"); +const printStatusLink = document.getElementById("print-status-link"); +const recentJobsLink = document.getElementById("recent-jobs-link"); +const printActionRow = document.getElementById("print-action-row"); +const uiLink = document.getElementById("ui-link"); +const uiFacts = document.getElementById("ui-facts"); +const logoutCSRF = document.getElementById("logout-csrf"); +const settingsPanel = document.getElementById("printer-settings-panel"); +const settingsSyncPill = document.getElementById("settings-sync-pill"); +const settingsSyncSummary = document.getElementById("settings-sync-summary"); +const printStatusFacts = document.getElementById("print-status-facts"); +const recentJobsList = document.getElementById("recent-jobs-list"); +const printActionBanner = document.getElementById("print-action-banner"); +const mmuMaterials = document.getElementById("mmu-materials"); +const mmuMaterialsFacts = document.getElementById("mmu-materials-facts"); +const temperaturePanel = document.getElementById("temperature-panel"); +const temperatureFacts = document.getElementById("temperature-facts"); +const adminLink = document.getElementById("admin-link"); +const agentLink = document.getElementById("agent-link"); +const settingsLink = document.getElementById("settings-link"); +const settingsEditLink = document.getElementById("settings-edit-link"); +const settingsFacts = document.getElementById("settings-facts"); + +const printerID = decodeURIComponent(window.location.pathname.replace(/^\/printers\//, "").split("/")[0] || ""); +const liveCameras = new Set(); +let currentCameraSignature = ""; +let printStatusRequestInFlight = false; +let currentControlMode = "readonly"; +let currentTemperatureSummary = ""; +let currentPrintState = ""; +let printActionBannerTimer = null; +const printActionConfirmationTimeoutMs = 5000; +const printActionConfirmationPollMs = 500; +const recentJobReplayInFlight = new Set(); +let recentJobReplayModal = null; +let recentJobReplayModalResolver = null; +let recentJobReplayModalKeyHandler = null; + +async function loadSession() { + const response = await fetch("/api/session", { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return; + } + const session = await response.json(); + if (!session.authenticated) { + window.location.href = "/login"; + return; + } + window.__KA_SESSION__ = session; + logoutCSRF.value = session.csrf_token || ""; + if (settingsPanel) { + settingsPanel.hidden = !session.is_admin; + } + if (agentLink && printerID) { + agentLink.href = `/printers/${encodeURIComponent(printerID)}/agent`; + } + if (adminLink && printerID) { + adminLink.href = `/admin?printer_id=${encodeURIComponent(printerID)}`; + } + if (settingsLink && printerID) { + settingsLink.href = `/printers/${encodeURIComponent(printerID)}/settings`; + } + if (settingsEditLink && printerID) { + settingsEditLink.href = `/printers/${encodeURIComponent(printerID)}/settings`; + } +} + +async function loadPrinter() { + if (!printerID) { + title.textContent = "Unknown printer"; + return; + } + + title.textContent = printerID; + healthLink.href = `/api/printers/${encodeURIComponent(printerID)}/health`; + infoLink.href = `/p/${encodeURIComponent(printerID)}/moonraker/printer/info`; + if (printStatusLink) { + printStatusLink.href = `/p/${encodeURIComponent(printerID)}/moonraker/printer/objects/query?print_stats&display_status`; + } + if (recentJobsLink) { + recentJobsLink.href = `/p/${encodeURIComponent(printerID)}/moonraker/server/history/list?limit=5&order=desc`; + } + const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}`, { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return; + } + if (!response.ok) { + renderHealth(null, false); + infoFacts.innerHTML = fact("Moonraker", `Unavailable (${response.status})`); + renderPrintStatus(null, `HTTP ${response.status}`, "readonly"); + return; + } + const data = await response.json(); + renderHealth(data, true); + const label = (data.settings && data.settings.display_name ? String(data.settings.display_name).trim() : "") || printerID; + title.textContent = label; + const syncState = computeSettingsSync(data.settings || {}, data.health || {}); + currentControlMode = data.control_mode || "readonly"; + const detailPrintStatus = data.health?.print_status || data.print_status || null; + currentTemperatureSummary = formatTemperatureSummary(detailPrintStatus); + renderUI(data.health || {}, data.settings || {}, data.control_mode || "readonly", data.access || "unknown", syncState); + renderPrintStatus(data.print_status || data.health?.print_status || null, data.print_status_error || "", data.control_mode || "readonly"); + renderMmuMaterials(detailPrintStatus); + renderTemperatureFacts(detailPrintStatus); + renderRecentJobs(data.recent_jobs || [], data.recent_jobs_error || ""); + renderSettings(data.health || {}, data.settings || {}, data.control_mode || "readonly", syncState); + updateUILink(data.health || {}); + if (data.info) { + renderInfo(data.info); + return; + } + infoFacts.innerHTML = fact("Moonraker", data.info_error || "No printer info available."); +} + +function renderMmuMaterials(printStatus) { + if (!mmuMaterials || !mmuMaterialsFacts) { + return; + } + const state = collectMmuMaterialState(printStatus); + if (!state.visible) { + mmuMaterials.hidden = true; + mmuMaterialsFacts.innerHTML = ""; + return; + } + mmuMaterials.hidden = false; + mmuMaterialsFacts.innerHTML = state.disabled + ? mmuMaterialChipHtml({ label: state.label, value: "Disabled", color: "" }, true) + : state.rows.map((row) => mmuMaterialChipHtml(row, false)).join(""); +} + +function renderTemperatureFacts(printStatus) { + if (!temperaturePanel || !temperatureFacts) { + return; + } + const state = collectTemperatureState(printStatus); + if (!state.visible) { + temperaturePanel.hidden = true; + temperatureFacts.innerHTML = ""; + return; + } + temperaturePanel.hidden = false; + temperatureFacts.innerHTML = state.rows.map((row) => fact(row.label, row.value)).join(""); +} + +async function refreshPrintStatus() { + if (!printerID || printStatusRequestInFlight || !printStatusFacts) { + return; + } + printStatusRequestInFlight = true; + try { + const result = await fetchPrintStatus(); + if (!result.ok) { + renderPrintStatus(null, result.error, currentControlMode); + return; + } + renderPrintStatus(result.status, "", currentControlMode); + } catch (error) { + renderPrintStatus(null, error instanceof Error ? error.message : "failed to refresh print status", currentControlMode); + } finally { + printStatusRequestInFlight = false; + } +} + +async function fetchPrintStatus() { + const response = await fetch(`/p/${encodeURIComponent(printerID)}/moonraker/printer/objects/query?print_stats&display_status`, { + credentials: "same-origin", + }); + if (!response.ok) { + return { ok: false, error: `HTTP ${response.status}` }; + } + const payload = await response.json(); + return { + ok: true, + status: payload.result ? payload.result.status || payload.result : payload, + }; +} + +function renderUI(health, settings, controlMode, accessLevel, syncState) { + uiFacts.innerHTML = [ + fact("Reachable", health.ui_reachable ? "Yes" : "No"), + fact("Source", health.ui_source || "Unknown"), + fact("Configured UI", settings.ui_url || "Auto"), + fact("Agent UI", health.ui_url || "Unavailable"), + fact("Auto-detect", settings.ui_auto_detect ? "On" : "Off"), + fact("Desired mode", controlMode), + fact("Applied mode", health.control_mode || "Unknown"), + fact("Sync", syncState.state), + fact("Sync detail", syncState.detail), + fact("Access", accessLevel || "Unknown"), + ].join(""); +} + +function renderSettings(health, settings, controlMode, syncState) { + if (!settingsPanel || settingsPanel.hidden) { + return; + } + if (settingsSyncPill) { + settingsSyncPill.textContent = syncState.state; + settingsSyncPill.classList.toggle("ok", syncState.synced); + settingsSyncPill.classList.toggle("warn", !syncState.synced); + } + if (settingsSyncSummary) { + const appliedMode = health.control_mode || "Unknown"; + const lastSeen = health.checked_at_unix ? relativeTime(health.checked_at_unix) : "no heartbeat yet"; + settingsSyncSummary.textContent = `${syncState.detail} Last heartbeat ${lastSeen}; applied mode ${appliedMode}.`; + } + if (settingsFacts) { + settingsFacts.innerHTML = [ + fact("Display name", settings.display_name || "Not set"), + fact("Control mode", settings.control_mode || controlMode || "readonly"), + fact("UI URL", settings.ui_url || "Auto-detect"), + fact("Auto-detect", settings.ui_auto_detect ? "On" : "Off"), + fact("Agent UI", health.ui_url || "Unavailable"), + fact("Sync", syncState.state), + fact("Sync detail", syncState.detail), + ].join(""); + } +} + +function updateUILink(health) { + const uiRoute = `/printers/${encodeURIComponent(printerID)}/ui/`; + if (health.ui_reachable) { + uiLink.href = uiRoute; + uiLink.removeAttribute("aria-disabled"); + uiLink.classList.remove("disabled"); + uiLink.textContent = "Open Printer UI"; + return; + } + uiLink.href = "#"; + uiLink.setAttribute("aria-disabled", "true"); + uiLink.classList.add("disabled"); + uiLink.textContent = "UI unavailable"; +} + +function renderHealth(data, loaded) { + if (!loaded || !data) { + setStatus("Not reachable", false); + healthFacts.innerHTML = fact("Agent", "Unknown"); + renderCameras([]); + return; + } + + const health = data.health || {}; + const reachable = data.connected && health.moonraker_reachable === true; + setStatus(reachable ? (health.moonraker_state || "Reachable") : "Not reachable", reachable); + + const checked = health.checked_at_unix ? relativeTime(health.checked_at_unix) : "Waiting for heartbeat"; + healthFacts.innerHTML = [ + fact("Agent", data.connected ? "Connected" : "Disconnected"), + fact("Moonraker", health.moonraker_reachable ? "Reachable" : "Not reachable"), + fact("State", health.moonraker_state || "Unknown"), + fact("Message", health.moonraker_message || "No status message yet."), + fact("Agent version", health.agent_version || "Unknown"), + fact("Host", health.hostname || "Unknown"), + fact("Last heartbeat", checked), + ].join(""); + renderCameras(health.cameras || []); +} + +function renderInfo(info) { + infoFacts.innerHTML = [ + fact("Hostname", info.hostname || "Unknown"), + fact("Software", info.software_version || "Unknown"), + fact("CPU", info.cpu_info || "Unknown"), + fact("Config", info.config_file || "Unknown"), + fact("Log", info.log_file || "Unknown"), + ].join(""); +} + +function renderPrintStatus(status, error, controlMode) { + if (!printStatusFacts) { + return; + } + if (!status) { + currentPrintState = ""; + printStatusFacts.innerHTML = [ + fact("State", error ? `Unavailable (${error})` : "Unknown"), + ].join(""); + if (printActionRow) { + printActionRow.innerHTML = ""; + } + setPrintActionBanner("", ""); + return; + } + const printStats = status.print_stats || status; + const displayStatus = status.display_status || status; + const state = String(printStats.state || "Unknown"); + currentPrintState = normalizePrintState(state); + const filename = String(printStats.filename || "No file loaded"); + const progress = formatProgress(displayStatus.progress); + const duration = formatDuration(printStats.print_duration); + const totalDuration = formatDuration(printStats.total_duration); + const message = String(printStats.message || displayStatus.message || "No status message yet."); + const filamentUsed = formatFilament(printStats.filament_used); + const remaining = formatDuration(printStats.estimated_time_remaining || printStats.estimated_duration); + const rows = [ + fact("State", state), + fact("File", filename), + fact("Progress", progress), + fact("Print duration", duration), + fact("Total duration", totalDuration), + fact("Remaining", remaining), + fact("Filament", filamentUsed), + fact("Message", message), + ]; + if (currentTemperatureSummary) { + rows.push(fact("Temps", currentTemperatureSummary)); + } + printStatusFacts.innerHTML = rows.join(""); + renderPrintActionRow(state, controlMode); +} + +function collectMmuMaterialState(printStatus) { + if (!printStatus || typeof printStatus !== "object") { + return { visible: false, disabled: false, label: "MMU", rows: [] }; + } + const mmu = printStatus.moonraker_status && printStatus.moonraker_status.mmu; + if (!mmu || typeof mmu !== "object" || !Object.prototype.hasOwnProperty.call(mmu, "enabled")) { + return { visible: false, disabled: false, label: "MMU", rows: [] }; + } + const machine = printStatus.moonraker_status && printStatus.moonraker_status.mmu_machine; + const label = machine?.unit_0?.name || "MMU"; + if (!isTruthyMetadataValue(mmu.enabled)) { + return { visible: true, disabled: true, label, rows: [] }; + } + const names = normalizeMetadataList(mmu.gate_filament_name); + const materials = normalizeMetadataList(mmu.gate_material); + const colors = normalizeMetadataList(mmu.gate_color); + const count = Math.max(names.length, materials.length, colors.length, Number(mmu.num_gates || 0)); + if (count === 0) { + return { visible: true, disabled: false, label, rows: [{ label, value: "Enabled" }] }; + } + return { + visible: true, + disabled: false, + label, + rows: Array.from({ length: count }, (_, index) => { + const parts = []; + let color = ""; + if (names[index] && names[index] !== "Unknown") { + parts.push(String(names[index])); + } + if (materials[index] && materials[index] !== names[index]) { + parts.push(`(${String(materials[index])})`); + } + if (colors[index]) { + color = String(colors[index]).replace(/[^0-9a-fA-F]/g, ""); + } + return { + label: `Gate ${index + 1}`, + value: parts.join(" ") || "Unknown material", + color, + }; + }), + }; +} + +function normalizeMetadataList(value) { + if (Array.isArray(value)) { + return value.filter((item) => item !== null && item !== undefined && item !== ""); + } + if (value === null || value === undefined || value === "") { + return []; + } + return [value]; +} + +function isTruthyMetadataValue(value) { + if (Array.isArray(value)) { + return value.length > 0; + } + if (typeof value === "string") { + const normalized = value.trim().toLowerCase(); + return normalized === "1" || normalized === "true" || normalized === "yes"; + } + return Boolean(value); +} + +function mmuMaterialChipHtml(row, disabled) { + const label = escapeHTML(row && row.label ? row.label : ""); + const value = row && row.value ? escapeHTML(row.value) : ""; + const color = row && row.color ? mmuNormalizeHexColor(row.color) : ""; + const style = color ? ` style="--mmu-swatch:${escapeHTML(color)}"` : ""; + const classes = ["mmu-material-chip"]; + if (disabled) { + classes.push("mmu-disabled"); + } + return `${label}${value ? ` ${value}` : ""}`; +} + +function mmuNormalizeHexColor(value) { + const raw = String(value || "").trim().replace(/[^0-9a-fA-F]/g, ""); + if (raw.length === 8) { + return `#${raw.slice(0, 6)}`; + } + if (raw.length === 6) { + return `#${raw}`; + } + if (raw.length === 3) { + return `#${raw.split("").map((ch) => ch + ch).join("")}`; + } + return ""; +} + +function formatTemperatureSummary(printStatus) { + const state = collectTemperatureState(printStatus); + if (!state.visible) { + return ""; + } + return state.rows.map((row) => `${row.label} ${row.value}`).join(" ยท "); +} + +function collectTemperatureState(printStatus) { + const status = printStatus && printStatus.moonraker_status; + if (!status || typeof status !== "object") { + return { visible: false, rows: [] }; + } + const rows = []; + const seen = new Set(); + const add = (key, label) => { + if (!Object.prototype.hasOwnProperty.call(status, key)) { + return; + } + const sensor = status[key]; + if (!sensor || typeof sensor !== "object") { + return; + } + const value = formatTemperatureReading(sensor); + if (!value) { + return; + } + rows.push({ label, value }); + seen.add(key); + }; + add("extruder", "Hotend"); + add("heater_bed", "Bed"); + add("temperature_sensor chamber", "Chamber"); + Object.keys(status).sort().forEach((key) => { + if (seen.has(key) || !isTemperatureSensorKey(key)) { + return; + } + const sensor = status[key]; + if (!sensor || typeof sensor !== "object") { + return; + } + const value = formatTemperatureReading(sensor); + if (!value) { + return; + } + rows.push({ label: prettifyTemperatureLabel(key), value }); + }); + return { visible: rows.length > 0, rows }; +} + +function isTemperatureSensorKey(key) { + return typeof key === "string" && ( + key.startsWith("temperature_sensor ") || + key.startsWith("temperature_fan ") || + key.startsWith("temperature_probe ") + ); +} + +function prettifyTemperatureLabel(key) { + const raw = String(key || "") + .replace(/^temperature_(sensor|fan|probe)\s+/i, "") + .replace(/_/g, " ") + .trim(); + if (!raw) { + return "Sensor"; + } + return raw.replace(/\b\w/g, (ch) => ch.toUpperCase()); +} + +function formatTemperatureReading(sensor) { + const current = Number(sensor.temperature); + if (!Number.isFinite(current)) { + return ""; + } + const target = Number(sensor.target); + if (Number.isFinite(target) && target > 0) { + return `${current.toFixed(1)} / ${target.toFixed(1)}\u00b0C`; + } + return `${current.toFixed(1)}\u00b0C`; +} + +function renderPrintActionRow(state, controlMode) { + if (!printActionRow) { + return; + } + const isFull = String(controlMode || "").toLowerCase() === "full"; + const normalizedState = String(state || "").toLowerCase(); + printActionRow.innerHTML = [ + printActionButton("Pause", "pause", "secondary", isFull && normalizedState === "printing"), + printActionButton("Resume", "resume", "primary", isFull && normalizedState === "paused"), + printActionButton("Cancel", "cancel", "secondary", isFull && (normalizedState === "printing" || normalizedState === "paused" || normalizedState === "resuming")), + printActionButton("Emergency Stop", "emergency_stop", "danger", isFull), + ].join(""); + bindPrintActions(); +} + +function printActionButton(label, action, kind, enabled) { + const disabled = enabled ? "" : " disabled aria-disabled=\"true\""; + const title = enabled ? "" : " title=\"Unavailable in the current print state\""; + return ``; +} + +function setPrintActionBanner(message, kind) { + if (!printActionBanner) { + return; + } + if (printActionBannerTimer) { + clearTimeout(printActionBannerTimer); + printActionBannerTimer = null; + } + const text = String(message || "").trim(); + if (!text) { + printActionBanner.hidden = true; + printActionBanner.textContent = ""; + printActionBanner.className = "print-action-banner"; + return; + } + printActionBanner.hidden = false; + printActionBanner.textContent = text; + printActionBanner.className = `print-action-banner ${escapeHTML(kind || "info")}`; + printActionBannerTimer = setTimeout(() => { + if (!printActionBanner) { + return; + } + printActionBanner.hidden = true; + printActionBanner.textContent = ""; + printActionBanner.className = "print-action-banner"; + printActionBannerTimer = null; + }, 8000); +} + +function normalizePrintState(value) { + return String(value || "").trim().toLowerCase(); +} + +function prettyPrintAction(action) { + if (action === "emergency_stop") { + return "Emergency stop"; + } + return action.charAt(0).toUpperCase() + action.slice(1); +} + +function isPrintActionConfirmed(action, state) { + const normalized = normalizePrintState(state); + if (!normalized) { + return false; + } + switch (action) { + case "pause": + return normalized === "paused"; + case "resume": + return normalized === "printing"; + case "cancel": + return normalized === "cancelled" || normalized === "canceled" || normalized === "idle" || normalized === "standby" || normalized === "error"; + default: + return false; + } +} + +async function waitForPrintActionConfirmation(action, baselineState) { + const deadline = Date.now() + printActionConfirmationTimeoutMs; + let lastState = normalizePrintState(baselineState); + while (Date.now() < deadline) { + await sleep(printActionConfirmationPollMs); + let result; + try { + result = await fetchPrintStatus(); + } catch { + continue; + } + if (!result.ok) { + continue; + } + const payload = result.status || {}; + const printStats = payload.print_stats || payload; + const state = normalizePrintState(printStats.state || "Unknown"); + lastState = state || lastState; + if (isPrintActionConfirmed(action, state)) { + return { confirmed: true, state }; + } + } + return { confirmed: false, state: lastState || "unknown" }; +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function runPrintAction(action) { + if (!printerID) { + return; + } + const baselineState = currentPrintState; + setPrintActionBanner(`Sending ${prettyPrintAction(action).toLowerCase()}...`, "info"); + const response = await fetch(`/p/${encodeURIComponent(printerID)}/moonraker/printer/print/${encodeURIComponent(action)}`, { + method: "POST", + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + }, + body: "{}", + }); + if (response.status === 403) { + const text = await response.text(); + setStatus("Not reachable", false); + renderPrintStatus(null, text || "blocked by read-only printer control policy", currentControlMode); + setPrintActionBanner(text || "blocked by read-only printer control policy", "error"); + return; + } + if (!response.ok) { + const text = `HTTP ${response.status}`; + renderPrintStatus(null, text, currentControlMode); + setPrintActionBanner(text, "error"); + return; + } + if (action === "emergency_stop") { + setPrintActionBanner("Emergency stop accepted.", "success"); + await loadPrinter(); + return; + } + setPrintActionBanner(`${prettyPrintAction(action)} accepted. Confirming state...`, "info"); + const confirmation = await waitForPrintActionConfirmation(action, baselineState); + if (confirmation.confirmed) { + setPrintActionBanner(`${prettyPrintAction(action)} confirmed: ${confirmation.state}.`, "success"); + } else { + setPrintActionBanner(`${prettyPrintAction(action)} sent. Current state: ${confirmation.state}.`, "warn"); + } + await loadPrinter(); +} + +async function replayRecentJob(filename, label, button) { + if (!printerID || !filename) { + return; + } + const normalizedLabel = String(label || "print again").trim() || "print again"; + const key = filename; + if (recentJobReplayInFlight.has(key)) { + return; + } + recentJobReplayInFlight.add(key); + if (button) { + button.disabled = true; + } + setPrintActionBanner(`Starting ${normalizedLabel.toLowerCase()}...`, "info"); + try { + const response = await fetch(`/p/${encodeURIComponent(printerID)}/moonraker/printer/print/start?filename=${encodeURIComponent(filename)}`, { + method: "POST", + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + }, + body: "{}", + }); + if (response.status === 403) { + const text = await response.text(); + setPrintActionBanner(text || "blocked by read-only printer control policy", "error"); + return; + } + if (!response.ok) { + const text = await response.text(); + setPrintActionBanner(text || `HTTP ${response.status}`, "error"); + return; + } + setPrintActionBanner(`${normalizedLabel} accepted. Refreshing printer state...`, "success"); + setTimeout(loadPrinter, 1000); + } catch (error) { + setPrintActionBanner(error instanceof Error ? error.message : `Failed to start ${normalizedLabel.toLowerCase()}.`, "error"); + } finally { + recentJobReplayInFlight.delete(key); + if (button) { + button.disabled = false; + } + } +} + +function closeRecentJobReplayModal(result) { + if (recentJobReplayModalKeyHandler) { + document.removeEventListener("keydown", recentJobReplayModalKeyHandler); + recentJobReplayModalKeyHandler = null; + } + if (recentJobReplayModal) { + recentJobReplayModal.remove(); + recentJobReplayModal = null; + } + if (recentJobReplayModalResolver) { + const resolve = recentJobReplayModalResolver; + recentJobReplayModalResolver = null; + resolve(result); + } +} + +function openRecentJobReplayModal(job) { + if (recentJobReplayModal) { + closeRecentJobReplayModal(false); + } + return new Promise((resolve) => { + recentJobReplayModalResolver = resolve; + const backdrop = document.createElement("div"); + backdrop.className = "modal-backdrop"; + backdrop.innerHTML = ` + + `; + const cancelButton = backdrop.querySelector("[data-replay-cancel]"); + const confirmButton = backdrop.querySelector("[data-replay-confirm]"); + const finish = (value) => { + if (recentJobReplayModal === backdrop) { + closeRecentJobReplayModal(value); + } + }; + backdrop.addEventListener("click", (event) => { + if (event.target === backdrop) { + finish(false); + } + }); + cancelButton.addEventListener("click", () => finish(false)); + confirmButton.addEventListener("click", () => finish(true)); + recentJobReplayModalKeyHandler = (event) => { + if (recentJobReplayModal !== backdrop) { + return; + } + if (event.key === "Escape") { + event.preventDefault(); + finish(false); + } + }; + document.addEventListener("keydown", recentJobReplayModalKeyHandler); + recentJobReplayModal = backdrop; + document.body.appendChild(backdrop); + confirmButton.focus(); + }); +} + +function bindPrintActions() { + if (!printActionRow) { + return; + } + printActionRow.querySelectorAll("[data-print-action]").forEach((button) => { + button.addEventListener("click", async () => { + if (button.disabled) { + return; + } + const action = button.dataset.printAction; + if (!action) { + return; + } + button.disabled = true; + try { + await runPrintAction(action); + } finally { + button.disabled = false; + } + }); + }); +} + +function renderRecentJobs(jobs, error) { + if (!recentJobsList) { + return; + } + if (!Array.isArray(jobs) || jobs.length === 0) { + recentJobsList.innerHTML = `

${escapeHTML(error || "No recent jobs found.")}

`; + return; + } + recentJobsList.innerHTML = jobs.map((job) => { + const filename = String(job.filename || "Unknown job"); + const status = String(job.status || "unknown"); + const normalizedStatus = status.toLowerCase(); + const duration = formatDuration(job.total_duration || job.print_duration); + const started = formatHistoryTime(job.start_time); + const ended = formatHistoryTime(job.end_time); + const message = String(job.message || ""); + const isFullControl = String(currentControlMode || "").toLowerCase() === "full"; + const canReplay = isFullControl && ["completed", "cancelled", "canceled", "failed", "error", "aborted"].includes(normalizedStatus); + const replayLabel = normalizedStatus === "completed" ? "Print again" : (["failed", "error"].includes(normalizedStatus) ? "Restart" : "Reprint"); + const replayTitle = canReplay ? "" : " title=\"Unavailable in the current print state\""; + return ` +
+
+ ${escapeHTML(filename)} + ${escapeHTML(status)} +
+
+
Duration
${escapeHTML(duration)}
+
Started
${escapeHTML(started)}
+
Ended
${escapeHTML(ended)}
+
Message
${escapeHTML(message || "No message")}
+
+
+ +
+
+ `; + }).join(""); + bindRecentJobActions(); +} + +function bindRecentJobActions() { + if (!recentJobsList) { + return; + } + recentJobsList.querySelectorAll("[data-job-filename]").forEach((button) => { + button.addEventListener("click", async () => { + if (button.disabled) { + return; + } + const filename = button.dataset.jobFilename; + const label = button.dataset.jobLabel || "Print again"; + const statusLabel = button.closest(".job-row")?.querySelector(".status-pill")?.textContent || "unknown"; + if (!filename) { + return; + } + try { + const confirmed = await openRecentJobReplayModal({ + filename, + statusLabel, + actionLabel: label, + }); + if (!confirmed) { + return; + } + await replayRecentJob(filename, label, button); + } finally { + closeRecentJobReplayModal(false); + } + }); + }); +} + +function renderCameras(cameras) { + const signature = JSON.stringify(cameras.map((camera) => ({ + name: camera.name, + has_snapshot: camera.has_snapshot, + has_stream: camera.has_stream, + aspect_ratio: camera.aspect_ratio, + rotation: camera.rotation, + flip_horizontal: camera.flip_horizontal, + flip_vertical: camera.flip_vertical, + }))); + if (signature === currentCameraSignature) { + return; + } + currentCameraSignature = signature; + + if (cameras.length === 0) { + cameraList.innerHTML = '

No cameras are configured for this agent.

'; + return; + } + + cameraList.innerHTML = cameras.map((camera) => { + const cameraKey = camera.name; + const snapshotURL = `/p/${encodeURIComponent(printerID)}/camera/${encodeURIComponent(camera.name)}/snapshot`; + const streamURL = `/p/${encodeURIComponent(printerID)}/camera/${encodeURIComponent(camera.name)}/stream`; + const live = liveCameras.has(cameraKey); + const transform = cameraTransform(camera); + const aspect = camera.aspect_ratio ? camera.aspect_ratio.replace(":", " / ") : "16 / 9"; + const preview = camera.has_snapshot + ? `${escapeHTML(camera.name)} camera preview` + : '
No snapshot
'; + const streamLink = camera.has_stream + ? `Open Stream` + : ""; + const liveToggle = camera.has_stream && camera.has_snapshot + ? `` + : ""; + const snapshotLink = camera.has_snapshot + ? `Snapshot` + : ""; + + return ` +
+ ${preview} + +
+ `; + }).join(""); + bindCameraControls(); + refreshSnapshots(); +} + +function bindCameraControls() { + document.querySelectorAll(".camera-live-toggle").forEach((button) => { + button.addEventListener("click", () => { + const cameraName = button.dataset.cameraName; + if (!cameraName) { + return; + } + const image = document.querySelector(`.camera-preview[data-camera-name="${cssEscape(cameraName)}"]`); + if (!image) { + return; + } + const currentlyLive = liveCameras.has(cameraName); + if (currentlyLive) { + liveCameras.delete(cameraName); + image.dataset.live = "false"; + image.src = withCacheBust(image.dataset.snapshotUrl); + button.textContent = "Live Preview"; + } else { + liveCameras.add(cameraName); + image.dataset.live = "true"; + image.src = image.dataset.streamUrl; + button.textContent = "Show Snapshot"; + } + }); + }); +} + +function refreshSnapshots() { + document.querySelectorAll(".camera-preview[data-live='false']").forEach((image) => { + if (image.dataset.snapshotUrl) { + image.src = withCacheBust(image.dataset.snapshotUrl); + } + }); +} + +cameraList.addEventListener("error", (event) => { + const image = event.target; + if (!image.classList || !image.classList.contains("camera-preview")) { + return; + } + const count = Number(image.dataset.errorCount || "0") + 1; + image.dataset.errorCount = String(count); + if (count >= 3) { + image.classList.add("camera-preview-error"); + image.alt = `${image.dataset.cameraName || "Camera"} unavailable`; + } +}, true); + +cameraList.addEventListener("load", (event) => { + const image = event.target; + if (!image.classList || !image.classList.contains("camera-preview")) { + return; + } + image.dataset.errorCount = "0"; + image.classList.remove("camera-preview-error"); +}, true); + +function withCacheBust(url) { + return `${url}${url.includes("?") ? "&" : "?"}t=${Date.now()}`; +} + +function cssEscape(value) { + if (window.CSS && CSS.escape) { + return CSS.escape(value); + } + return String(value).replaceAll('"', '\\"'); +} + +function cameraTransform(camera) { + const transforms = []; + if (camera.flip_horizontal) { + transforms.push("scaleX(-1)"); + } + if (camera.flip_vertical) { + transforms.push("scaleY(-1)"); + } + if (camera.rotation) { + transforms.push(`rotate(${Number(camera.rotation)}deg)`); + } + return transforms.join(" ") || "none"; +} + +function cameraMeta(camera) { + const parts = []; + if (camera.location) { + parts.push(camera.location); + } + if (camera.service) { + parts.push(camera.service); + } + if (camera.source) { + parts.push(camera.source); + } + return parts.join(" / ") || "Configured camera"; +} + +function relativeTime(unixSeconds) { + const seconds = Math.max(0, Math.floor(Date.now() / 1000) - unixSeconds); + if (seconds < 5) { + return "just now"; + } + if (seconds < 60) { + return `${seconds}s ago`; + } + const minutes = Math.floor(seconds / 60); + if (minutes < 60) { + return `${minutes}m ago`; + } + const hours = Math.floor(minutes / 60); + return `${hours}h ago`; +} + +function setStatus(label, ok) { + status.textContent = label; + status.classList.toggle("ok", ok); + status.classList.toggle("warn", !ok); +} + +function fact(label, value) { + return `
${escapeHTML(label)}
${escapeHTML(value)}
`; +} + +function computeSettingsSync(settings, health) { + const updatedAt = parseTimestamp(settings.updated_at); + const lastSyncedAt = parseTimestamp(settings.last_synced_at); + const controlMode = String(settings.control_mode || "").toLowerCase() || "readonly"; + const appliedMode = String(health.control_mode || "").toLowerCase() || "unknown"; + const uiURL = String(settings.ui_url || "").trim(); + const agentUIURL = String(health.ui_url || "").trim(); + const autoDetect = Boolean(settings.ui_auto_detect); + const agentAutoDetect = Boolean(health.ui_auto_detect); + const synced = Boolean(updatedAt && lastSyncedAt && lastSyncedAt >= updatedAt); + if (synced) { + return { + synced: true, + state: "Synced", + detail: "Agent acknowledged the latest saved settings.", + }; + } + const detailBits = []; + if (controlMode !== appliedMode && appliedMode !== "unknown") { + detailBits.push(`control mode ${controlMode} -> ${appliedMode}`); + } + if (uiURL && uiURL !== agentUIURL) { + detailBits.push(`UI URL ${uiURL} -> ${agentUIURL || "unset"}`); + } + if (autoDetect !== agentAutoDetect) { + detailBits.push(`auto-detect ${autoDetect} -> ${agentAutoDetect}`); + } + return { + synced: false, + state: "Pending", + detail: detailBits.length > 0 ? `Waiting for agent confirmation; ${detailBits.join("; ")}` : "Waiting for the agent to confirm the latest settings.", + }; +} + +function parseTimestamp(value) { + if (!value) { + return 0; + } + const parsed = Date.parse(value); + return Number.isFinite(parsed) ? parsed : 0; +} + +function formatProgress(value) { + const progress = Number(value); + if (!Number.isFinite(progress) || progress <= 0) { + return "0%"; + } + if (progress <= 1) { + return `${Math.round(progress * 100)}%`; + } + return `${Math.round(progress)}%`; +} + +function formatDuration(value) { + const seconds = Number(value); + if (!Number.isFinite(seconds) || seconds < 0) { + return "Unknown"; + } + const whole = Math.floor(seconds); + const hours = Math.floor(whole / 3600); + const minutes = Math.floor((whole % 3600) / 60); + const secs = whole % 60; + if (hours > 0) { + return `${hours}h ${minutes}m ${secs}s`; + } + if (minutes > 0) { + return `${minutes}m ${secs}s`; + } + return `${secs}s`; +} + +function formatFilament(value) { + const number = Number(value); + if (!Number.isFinite(number) || number <= 0) { + return "Unknown"; + } + return `${number.toFixed(1)} mm`; +} + +function formatHistoryTime(value) { + const unix = Number(value); + if (!Number.isFinite(unix) || unix <= 0) { + return "Unknown"; + } + return new Date(unix * 1000).toLocaleString(); +} + +function escapeHTML(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +refresh.addEventListener("click", loadPrinter); +loadSession().then(loadPrinter); +setInterval(loadPrinter, 15000); +setInterval(refreshPrintStatus, 500); +setInterval(refreshSnapshots, 500); diff --git a/web/static/session.js b/web/static/session.js new file mode 100644 index 0000000..e895bc7 --- /dev/null +++ b/web/static/session.js @@ -0,0 +1,59 @@ +async function applySessionState() { + let session; + try { + const response = await fetch("/api/session", { credentials: "same-origin" }); + if (!response.ok) { + return; + } + session = await response.json(); + } catch { + return; + } + + window.__KA_SESSION__ = session; + const isLoggedIn = session.authenticated === true; + document.querySelectorAll(".logged-in-only").forEach((element) => { + setVisible(element, isLoggedIn); + }); + document.querySelectorAll(".logged-out-only").forEach((element) => { + setVisible(element, !isLoggedIn); + }); + document.querySelectorAll(".admin-only").forEach((element) => { + setVisible(element, isLoggedIn && session.is_admin === true); + }); + markCurrentNavLink(); + + const csrf = document.getElementById("landing-csrf"); + if (csrf && session.csrf_token) { + csrf.value = session.csrf_token; + } +} + +function setVisible(element, visible) { + element.hidden = !visible; + element.style.display = visible ? "" : "none"; +} + +function markCurrentNavLink() { + const currentPath = normalizePath(window.location.pathname); + document.querySelectorAll(".nav-links a").forEach((link) => { + const href = link.getAttribute("href"); + if (!href || href === "#" || href.startsWith("http")) { + return; + } + const targetPath = normalizePath(new URL(href, window.location.origin).pathname); + const isCurrent = targetPath === currentPath; + link.classList.toggle("current", isCurrent); + if (isCurrent) { + link.setAttribute("aria-current", "page"); + } else { + link.removeAttribute("aria-current"); + } + }); +} + +function normalizePath(path) { + return String(path || "").replace(/\/+$/, "") || "/"; +} + +window.__KA_SESSION_PROMISE__ = applySessionState(); diff --git a/web/static/styles.css b/web/static/styles.css new file mode 100644 index 0000000..a5600ec --- /dev/null +++ b/web/static/styles.css @@ -0,0 +1,1406 @@ +:root { + color-scheme: dark; + --ink: #f7f3eb; + --muted: #c9d2c8; + --panel: rgba(14, 18, 20, 0.72); + --line: rgba(255, 255, 255, 0.16); + --teal: #48d4bf; + --amber: #f2b84b; + --charcoal: #111619; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + min-width: 320px; + background: var(--charcoal); + color: var(--ink); + font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + letter-spacing: 0; +} + +a { + color: inherit; + text-decoration: none; +} + +.site-header { + position: fixed; + z-index: 10; + top: 0; + right: 0; + left: 0; + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; + padding: 18px clamp(18px, 4vw, 56px); + background: linear-gradient(180deg, rgba(10, 13, 14, 0.82), rgba(10, 13, 14, 0)); +} + +.brand, +.nav-links { + display: flex; + align-items: center; +} + +.brand { + gap: 10px; + font-weight: 760; +} + +.brand-mark { + display: grid; + width: 32px; + height: 32px; + place-items: center; + border: 1px solid rgba(72, 212, 191, 0.44); + border-radius: 8px; + background: rgba(72, 212, 191, 0.12); + color: var(--teal); +} + +.nav-links { + width: 100%; + gap: 12px; + color: var(--muted); + font-size: 0.94rem; + font-weight: 650; +} + +.nav-group { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; +} + +.nav-core { + flex: 1 1 auto; +} + +.nav-tools { + margin-left: auto; + justify-content: flex-end; +} + +.printer-switcher-group { + display: flex; + align-items: center; + gap: 8px; + padding: 6px 10px; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 999px; + background: rgba(255, 255, 255, 0.03); +} + +.printer-switcher-label { + color: var(--muted); + font-size: 0.8rem; + font-weight: 700; + white-space: nowrap; +} + +.printer-switcher { + min-width: 160px; + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 999px; + padding: 8px 12px; + background: rgba(255, 255, 255, 0.05); + color: var(--ink); + font: inherit; + font-size: 0.92rem; + font-weight: 650; + appearance: auto; +} + +.printer-switcher:disabled { + opacity: 0.7; +} + +.printer-switcher option { + color: var(--charcoal); + background: var(--ink); +} + +.nav-links a:hover { + color: var(--ink); +} + +[hidden] { + display: none !important; +} + +.hero { + position: relative; + display: grid; + min-height: 86vh; + overflow: hidden; + align-items: center; + padding: 108px clamp(20px, 5vw, 72px) 72px; +} + +.hero-image, +.hero-shade { + position: absolute; + inset: 0; + width: 100%; + height: 100%; +} + +.hero-image { + object-fit: cover; +} + +.hero-shade { + background: + linear-gradient(90deg, rgba(7, 10, 11, 0.94) 0%, rgba(7, 10, 11, 0.74) 38%, rgba(7, 10, 11, 0.24) 76%), + linear-gradient(180deg, rgba(7, 10, 11, 0.1) 58%, var(--charcoal) 100%); +} + +.hero-content { + position: relative; + z-index: 1; + width: min(680px, 100%); +} + +.eyebrow { + margin: 0 0 14px; + color: var(--teal); + font-size: 0.83rem; + font-weight: 800; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +h1 { + margin: 0; + max-width: 11ch; + font-size: clamp(3.4rem, 10vw, 7.8rem); + line-height: 0.92; + letter-spacing: 0; +} + +.lede { + max-width: 650px; + margin: 24px 0 0; + color: var(--muted); + font-size: clamp(1.05rem, 2vw, 1.35rem); + line-height: 1.55; +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: 12px; + margin-top: 34px; +} + +.button { + display: inline-flex; + min-height: 46px; + align-items: center; + justify-content: center; + border: 1px solid var(--line); + border-radius: 8px; + padding: 0 18px; + font-weight: 760; + white-space: nowrap; +} + +.button.primary { + border-color: rgba(72, 212, 191, 0.8); + background: var(--teal); + color: #071010; +} + +.button.secondary { + background: rgba(255, 255, 255, 0.08); + color: var(--ink); +} + +.button.danger { + border-color: rgba(242, 77, 72, 0.5); + background: rgba(242, 77, 72, 0.12); + color: #ffd1cc; +} + +.button.disabled, +.button[aria-disabled="true"] { + opacity: 0.48; + pointer-events: none; +} + +.button:disabled { + opacity: 0.48; + cursor: not-allowed; +} + +.status-band { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 1px; + border-top: 1px solid var(--line); + border-bottom: 1px solid var(--line); + background: var(--line); +} + +.auth-page, +.app-page { + min-height: 100vh; + background: + linear-gradient(135deg, rgba(72, 212, 191, 0.12), transparent 42%), + #111619; +} + +.auth-shell { + display: grid; + min-height: 100vh; + align-content: center; + gap: 28px; + width: min(460px, calc(100% - 40px)); + margin: 0 auto; + padding: 48px 0; +} + +.auth-brand { + width: max-content; +} + +.auth-panel { + border: 1px solid var(--line); + border-radius: 8px; + padding: clamp(24px, 6vw, 36px); + background: rgba(21, 27, 29, 0.86); +} + +.auth-title, +.dashboard-title { + margin: 0; + max-width: none; + font-size: clamp(2.35rem, 6vw, 4.2rem); + line-height: 1; +} + +.auth-copy { + margin: 18px 0 0; + color: var(--muted); + line-height: 1.5; +} + +.login-form { + display: grid; + gap: 16px; + margin-top: 26px; +} + +.login-form label { + display: grid; + gap: 8px; + color: var(--muted); + font-size: 0.92rem; + font-weight: 700; +} + +.login-form input { + width: 100%; + min-height: 46px; + border: 1px solid var(--line); + border-radius: 8px; + padding: 0 12px; + background: rgba(255, 255, 255, 0.08); + color: var(--ink); + font: inherit; +} + +.login-form input:focus { + outline: 2px solid rgba(72, 212, 191, 0.7); + outline-offset: 2px; +} + +.form-error { + margin: 18px 0 0; + color: #ffb2a8; + font-weight: 700; +} + +.app-header { + position: sticky; + top: 0; + z-index: 9; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 14px 20px; + border-bottom: 1px solid var(--line); + padding: 16px clamp(18px, 4vw, 48px); + background: rgba(17, 22, 25, 0.92); + backdrop-filter: blur(10px); +} + +.text-button { + border: 0; + padding: 0; + background: transparent; + color: var(--muted); + font: inherit; + font-size: 0.94rem; + font-weight: 650; + cursor: pointer; +} + +.text-button:hover { + color: var(--ink); +} + +.nav-links a, +.nav-links button { + border-radius: 999px; + padding: 8px 13px; + transition: background-color 120ms ease, color 120ms ease, opacity 120ms ease; +} + +.nav-links a:hover, +.nav-links button:hover { + background: rgba(255, 255, 255, 0.06); +} + +.nav-links a.current { + background: rgba(72, 212, 191, 0.14); + color: var(--ink); + box-shadow: inset 0 0 0 1px rgba(72, 212, 191, 0.18); +} + +.logout-form { + margin: 0; +} + +.nav-links { + flex-wrap: wrap; + justify-content: flex-end; +} + +.users-shell { + gap: 18px; +} + +.account-shell { + gap: 18px; +} + +.audit-shell { + gap: 18px; +} + +.admin-shell { + gap: 18px; +} + +.install-shell { + gap: 18px; +} + +.dashboard-shell { + width: min(1180px, calc(100% - 40px)); + margin: 0 auto; + padding: clamp(32px, 6vw, 68px) 0; +} + +.dashboard-heading { + display: grid; + gap: 10px; + margin-bottom: 28px; +} + +.printer-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr)); + gap: 16px; +} + +.users-grid { + grid-template-columns: minmax(280px, 380px) minmax(0, 1fr); + align-items: start; +} + +.account-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + align-items: start; +} + +.audit-panel { + display: grid; + gap: 12px; +} + +.install-grid { + grid-template-columns: minmax(0, 1.2fr) minmax(0, 0.8fr); +} + +.admin-summary { + display: grid; + gap: 18px; +} + +.admin-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 16px; +} + +.admin-tile { + display: grid; + gap: 10px; + border: 1px solid var(--line); + border-radius: 8px; + padding: 18px; + background: rgba(255, 255, 255, 0.03); +} + +.admin-tile strong { + font-size: 1.2rem; + line-height: 1.2; +} + +.admin-tile p { + margin: 0; + color: var(--muted); + line-height: 1.5; +} + +.admin-printer-list { + display: grid; + gap: 12px; +} + +.admin-printer-row { + display: grid; + grid-template-columns: minmax(0, 1.4fr) minmax(260px, 1fr) auto; + gap: 16px; + align-items: center; + border: 1px solid var(--line); + border-radius: 8px; + padding: 16px 18px; + background: rgba(255, 255, 255, 0.03); +} + +.admin-printer-main { + min-width: 0; +} + +.admin-printer-main strong { + display: block; + font-size: 1.05rem; + line-height: 1.2; +} + +.admin-printer-main p { + margin: 6px 0 0; + color: var(--muted); + overflow-wrap: anywhere; +} + +.admin-printer-meta { + display: grid; + gap: 8px; + margin: 0; +} + +.admin-printer-meta div { + display: grid; + grid-template-columns: 90px minmax(0, 1fr); + gap: 10px; +} + +.admin-printer-meta dt { + color: var(--muted); + font-weight: 700; +} + +.admin-printer-meta dd { + margin: 0; + overflow-wrap: anywhere; +} + +.admin-printer-actions { + justify-content: flex-end; + margin-top: 0; +} + +.admin-version-facts { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.audit-list { + display: grid; + gap: 12px; +} + +.audit-event { + border: 1px solid var(--line); + border-radius: 8px; + padding: 14px; + background: rgba(255, 255, 255, 0.03); +} + +.audit-event-top { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 10px; +} + +.audit-time { + color: var(--muted); + font-size: 0.9rem; +} + +.audit-event-body { + display: flex; + flex-wrap: wrap; + gap: 8px; + color: var(--ink); + font-size: 0.95rem; +} + +.audit-event-body span { + display: inline-flex; + align-items: center; + min-height: 26px; + border: 1px solid var(--line); + border-radius: 999px; + padding: 0 10px; + background: rgba(255, 255, 255, 0.05); +} + +.audit-action { + border-color: rgba(72, 212, 191, 0.3); + color: var(--teal); +} + +.audit-detail { + margin: 10px 0 0; + color: var(--muted); +} + +.printer-card { + border: 1px solid var(--line); + border-radius: 8px; + padding: 22px; + background: #151b1d; +} + +.printer-card.healthy { + border-color: rgba(72, 212, 191, 0.28); +} + +.printer-card.unhealthy { + border-color: rgba(242, 184, 75, 0.32); +} + +.printer-thumb { + width: 100%; + aspect-ratio: 16 / 9; + border: 1px solid var(--line); + border-radius: 8px; + margin-bottom: 18px; + background: #0f1416; + object-fit: cover; +} + +.printer-thumb-empty { + display: grid; + place-items: center; + color: var(--muted); +} + +.printer-card-header { + display: flex; + justify-content: space-between; + gap: 16px; +} + +.printer-card h2 { + margin: 12px 0 0; + font-size: 1.45rem; + letter-spacing: 0; + overflow-wrap: anywhere; +} + +.status-pill { + display: inline-flex; + align-items: center; + min-height: 26px; + border: 1px solid var(--line); + border-radius: 999px; + padding: 0 10px; + font-size: 0.78rem; + font-weight: 800; +} + +.status-pill.ok { + border-color: rgba(72, 212, 191, 0.52); + color: var(--teal); +} + +.status-pill.warn { + border-color: rgba(242, 184, 75, 0.52); + color: var(--amber); +} + +.printer-facts { + display: grid; + gap: 12px; + margin: 22px 0 0; +} + +.printer-facts div { + display: grid; + grid-template-columns: 116px minmax(0, 1fr); + gap: 12px; +} + +.printer-facts dt { + color: var(--muted); + font-weight: 700; +} + +.printer-facts dd { + margin: 0; + overflow-wrap: anywhere; +} + +.mmu-materials { + display: grid; + gap: 12px; + margin-top: 18px; + padding: 16px; + border: 1px solid var(--line); + border-radius: 8px; + background: rgba(255, 255, 255, 0.03); +} + +.mmu-materials h3 { + margin: 0; + font-size: 1rem; +} + +.mmu-materials .printer-facts { + margin-top: 0; +} + +.temperature-summary { + font-variant-numeric: tabular-nums; +} + +.mmu-materials-value, +.mmu-material-chip-group { + display: flex; + flex-wrap: wrap; + gap: 10px; + align-items: center; +} + +.mmu-material-chip { + --mmu-swatch: #48d4bf; + display: inline-flex; + align-items: center; + gap: 10px; + min-height: 34px; + border: 1px solid var(--line); + border-radius: 999px; + padding: 4px 12px 4px 6px; + background: rgba(255, 255, 255, 0.05); +} + +.mmu-material-chip-swatch { + flex: 0 0 auto; + width: 18px; + height: 18px; + border-radius: 999px; + border: 1px solid rgba(255, 255, 255, 0.35); + background: var(--mmu-swatch); + box-shadow: inset 0 1px 1px rgba(255, 255, 255, 0.16); +} + +.mmu-material-chip-text { + display: inline-flex; + flex-wrap: wrap; + gap: 6px; + align-items: baseline; + color: var(--ink); +} + +.mmu-material-chip-text strong { + font-weight: 800; +} + +.mmu-material-chip.mmu-disabled { + opacity: 0.72; + background: rgba(255, 255, 255, 0.03); +} + +.mmu-material-chip.mmu-disabled .mmu-material-chip-swatch { + background: repeating-linear-gradient(135deg, rgba(255,255,255,0.2) 0 4px, rgba(255,255,255,0.08) 4px 8px); +} + +.card-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; + margin-top: 24px; +} + +.panel-actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 10px; + margin-top: 14px; +} + +.panel-actions .button { + min-width: 0; +} + +.empty-state { + margin: 0; + border: 1px solid var(--line); + border-radius: 8px; + padding: 22px; + background: #151b1d; + color: var(--muted); +} + +.form-message { + margin: 0 0 16px; + border: 1px solid var(--line); + border-radius: 8px; + padding: 12px 14px; + background: rgba(255, 255, 255, 0.06); + color: var(--muted); +} + +.form-message.success { + border-color: rgba(72, 212, 191, 0.4); + color: var(--teal); +} + +.form-message.error { + border-color: rgba(242, 184, 75, 0.45); + color: var(--amber); +} + +.user-form { + display: grid; + gap: 14px; +} + +.user-form label { + display: grid; + gap: 8px; + color: var(--muted); + font-size: 0.92rem; + font-weight: 700; +} + +.user-form input, +.user-form select, +.inline-input, +.inline-select, +.user-form textarea, +.inline-textarea { + width: 100%; + min-height: 42px; + border: 1px solid var(--line); + border-radius: 8px; + padding: 0 12px; + background: rgba(255, 255, 255, 0.08); + color: var(--ink); + font: inherit; +} + +.user-form textarea, +.inline-textarea { + min-height: 84px; + padding-top: 10px; + resize: vertical; +} + +.users-list { + min-width: 0; +} + +.users-card-list { + display: grid; + gap: 14px; +} + +.user-card { + border: 1px solid var(--line); + border-radius: 8px; + padding: 16px; + background: rgba(255, 255, 255, 0.03); +} + +.user-card-header { + display: flex; + align-items: start; + justify-content: space-between; + gap: 16px; + margin-bottom: 14px; +} + +.user-card-title { + display: block; + font-size: 1.05rem; + line-height: 1.2; +} + +.user-card-subtitle { + margin: 4px 0 0; + color: var(--muted); + font-size: 0.9rem; +} + +.user-card-fields { + display: grid; + grid-template-columns: minmax(180px, 220px) minmax(220px, 1fr); + gap: 14px; +} + +.user-card-fields .inline-select, +.user-card-fields .inline-input, +.user-card-fields .inline-textarea { + min-height: 46px; +} + +.user-card-fields label { + display: grid; + gap: 8px; + color: var(--muted); + font-size: 0.92rem; + font-weight: 700; +} + +.user-card-grants { + grid-column: 1 / -1; +} + +.user-card-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; + margin-top: 14px; +} + +.settings-form { + margin-top: 12px; +} + +.settings-applied { + margin-top: 18px; + padding-top: 18px; + border-top: 1px solid var(--line); +} + +.settings-applied-heading { + margin-bottom: 12px; +} + +.settings-applied-facts { + margin-top: 12px; +} + +.settings-select, +.install-form select[name="host_type"] { + color: var(--ink); + background: rgba(255, 255, 255, 0.08); + appearance: auto; + -webkit-appearance: menulist; +} + +.settings-select option, +.install-form select[name="host_type"] option { + color: #111619; + background: #f7f3eb; +} + +.install-form select[name="host_type"] { + min-height: 46px; + border: 1px solid var(--line); + border-radius: 8px; + padding: 0 12px; + font: inherit; +} + +.settings-form .button { + justify-self: start; +} + +.user-form .settings-checkbox { + display: flex !important; + flex-direction: row !important; + align-items: center !important; + justify-content: flex-start !important; + gap: 10px !important; + width: 100%; + color: var(--muted); + font-size: 0.92rem; + font-weight: 700; +} + +.user-form .settings-checkbox input { + flex: 0 0 auto; + width: 18px; + height: 18px; + margin: 0; + accent-color: var(--teal); +} + +.settings-checklist { + display: grid; + gap: 10px; +} + +.settings-subgroup { + margin-top: 6px; +} + +.modal-backdrop { + position: fixed; + inset: 0; + display: grid; + place-items: center; + padding: 24px; + background: rgba(0, 0, 0, 0.72); + z-index: 60; +} + +.modal-card { + width: min(100%, 440px); + border: 1px solid var(--line); + border-radius: 8px; + padding: 18px; + background: var(--panel); + box-shadow: 0 24px 70px rgba(0, 0, 0, 0.45); +} + +.modal-field { + display: grid; + gap: 8px; + margin-top: 14px; +} + +.modal-field span { + color: var(--muted); + font-size: 0.92rem; + font-weight: 700; +} + +.modal-actions { + display: flex; + justify-content: flex-end; + gap: 10px; + margin-top: 16px; +} + +.user-form .settings-checklist > .settings-checkbox { + display: flex !important; + flex-direction: row !important; + align-items: center !important; + justify-content: flex-start !important; + grid-template-columns: none !important; + grid-template-rows: none !important; +} + +.user-form .settings-checklist > .settings-checkbox > span { + display: inline !important; + min-width: 0; + flex: 1 1 auto; +} + +.install-form { + margin-top: 8px; +} + +.install-note { + margin-top: 12px; +} + +.install-output { + min-height: 220px; + margin: 0; + border: 1px solid var(--line); + border-radius: 8px; + padding: 16px; + background: rgba(255, 255, 255, 0.04); + color: var(--muted); + white-space: pre-wrap; + overflow: auto; +} + +.row-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.printer-detail-shell { + display: grid; + gap: 22px; +} + +.detail-hero { + display: flex; + align-items: end; + justify-content: space-between; + gap: 18px; + border-bottom: 1px solid var(--line); + padding-bottom: 24px; +} + +.detail-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; +} + +.detail-panel { + border: 1px solid var(--line); + border-radius: 8px; + padding: 22px; + background: #151b1d; +} + +.camera-panel { + grid-column: 1 / -1; +} + +.recent-jobs-list { + display: grid; + gap: 12px; +} + +.raw-json { + margin: 14px 0 0; + border: 1px solid var(--line); + border-radius: 8px; + padding: 14px; + background: rgba(255, 255, 255, 0.03); + color: var(--muted); + font-family: ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace; + font-size: 0.82rem; + line-height: 1.45; + white-space: pre-wrap; + overflow: auto; + max-height: 320px; +} + +.job-row { + display: grid; + gap: 10px; + border: 1px solid var(--line); + border-radius: 8px; + padding: 14px; + background: rgba(255, 255, 255, 0.03); +} + +.job-actions { + justify-content: flex-end; + margin-top: 4px; +} + +.job-row-top { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.job-row strong { + font-size: 1rem; + line-height: 1.2; + overflow-wrap: anywhere; +} + +.job-facts { + margin-top: 0; + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.print-action-row { + display: flex; + flex-wrap: wrap; + gap: 10px; + margin-top: 14px; +} + +.print-action-banner { + margin: 12px 0 0; + border: 1px solid var(--line); + border-radius: 8px; + padding: 10px 12px; + color: var(--muted); + background: rgba(255, 255, 255, 0.04); + line-height: 1.45; +} + +.print-action-banner.info { + border-color: rgba(72, 212, 191, 0.24); + color: var(--ink); +} + +.print-action-banner.success { + border-color: rgba(72, 212, 191, 0.36); + color: var(--teal); +} + +.print-action-banner.error { + border-color: rgba(242, 184, 75, 0.42); + color: var(--amber); +} + +.print-action-banner.warn { + border-color: rgba(242, 184, 75, 0.32); + color: var(--ink); +} + +.camera-list { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr)); + gap: 16px; +} + +.camera-card { + display: grid; + gap: 14px; +} + +.camera-preview { + width: 100%; + aspect-ratio: 16 / 9; + border: 1px solid var(--line); + border-radius: 8px; + background: #0f1416; + object-fit: cover; +} + +.camera-preview-error { + opacity: 0.42; + filter: grayscale(1); +} + +.camera-placeholder { + display: grid; + place-items: center; + color: var(--muted); +} + +.camera-card-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; +} + +.camera-card-footer p { + margin: 6px 0 0; + color: var(--muted); + font-size: 0.9rem; +} + +.panel-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + margin-bottom: 18px; +} + +.panel-heading > div:first-child { + min-width: 0; +} + +.panel-heading-stack { + display: grid; + justify-items: end; + gap: 8px; +} + +.panel-heading-inline { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 12px; +} + +.panel-heading-compact { + align-self: start; + margin-top: -4px; +} + +.panel-subtitle { + margin: 6px 0 0; + color: var(--muted); + font-size: 0.9rem; + line-height: 1.45; + overflow-wrap: anywhere; +} + +.panel-subtitle.status-info { + color: var(--muted); +} + +.panel-subtitle.status-ok { + color: var(--teal); +} + +.panel-subtitle.status-error { + color: var(--red); +} + +.panel-heading h2 { + margin: 0; + font-size: 1.25rem; + letter-spacing: 0; +} + +.panel-heading a { + color: var(--muted); + font-weight: 750; +} + +.panel-heading a:hover { + color: var(--ink); +} + +.detail-facts { + margin-top: 0; +} + +#moonraker-raw-facts div { + grid-template-columns: minmax(190px, 0.45fr) minmax(0, 1fr); + align-items: start; +} + +#moonraker-raw-facts dt, +#moonraker-raw-facts dd { + min-width: 0; + overflow-wrap: anywhere; +} + +#moonraker-raw-facts dd { + line-height: 1.45; +} + +.status-item { + min-height: 168px; + padding: clamp(22px, 4vw, 38px); + background: #151b1d; +} + +.status-kicker { + display: block; + margin-bottom: 12px; + color: var(--amber); + font-size: 0.78rem; + font-weight: 800; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.status-item strong { + display: block; + font-size: clamp(1.25rem, 2vw, 1.65rem); + letter-spacing: 0; +} + +.status-item p { + max-width: 34ch; + margin: 12px 0 0; + color: var(--muted); + line-height: 1.5; +} + +@media (max-width: 760px) { + .site-header { + position: absolute; + } + + .nav-links { + gap: 10px; + } + + .nav-core, + .nav-tools { + width: 100%; + } + + .nav-tools { + margin-left: 0; + justify-content: flex-start; + } + + .panel-heading { + align-items: start; + flex-direction: column; + } + + .panel-heading-stack { + justify-items: start; + } + + .hero { + min-height: 88vh; + padding-top: 96px; + } + + .hero-shade { + background: + linear-gradient(90deg, rgba(7, 10, 11, 0.9), rgba(7, 10, 11, 0.42)), + linear-gradient(180deg, rgba(7, 10, 11, 0.12) 44%, var(--charcoal) 100%); + } + + .button { + width: 100%; + } + + .status-band { + grid-template-columns: 1fr; + } + + .detail-hero { + align-items: start; + flex-direction: column; + } + + .detail-grid { + grid-template-columns: 1fr; + } + + .install-grid { + grid-template-columns: 1fr; + } + + .admin-grid { + grid-template-columns: 1fr; + } + + .admin-printer-row { + grid-template-columns: 1fr; + } + + .admin-printer-actions { + justify-content: flex-start; + } + + .admin-version-facts { + grid-template-columns: 1fr; + } +} diff --git a/web/static/users.html b/web/static/users.html new file mode 100644 index 0000000..703e043 --- /dev/null +++ b/web/static/users.html @@ -0,0 +1,94 @@ + + + + + + Users - KlipperAnywhere + + + + + + + + +
+ + + KlipperAnywhere + + +
+ +
+
+

Account management

+

Users

+
+ +
+
+
+

Add user

+
+

Create another login for family members or shared access on the same printer server.

+
+ + + + + +
+
+ +
+
+

Existing users

+
+

Loading users...

+
+
+
+
+ + + + + + + diff --git a/web/static/users.js b/web/static/users.js new file mode 100644 index 0000000..684b8e3 --- /dev/null +++ b/web/static/users.js @@ -0,0 +1,250 @@ +const csrfMeta = document.getElementById("csrf-meta"); +const refresh = document.getElementById("refresh"); +const status = document.getElementById("users-status"); +const list = document.getElementById("users-list"); +const createForm = document.getElementById("create-user-form"); + +let sessionCSRF = csrfMeta ? csrfMeta.content : ""; +let users = []; + +function setStatus(message, isError = false) { + if (!message) { + status.hidden = true; + status.textContent = ""; + status.classList.remove("error", "success"); + return; + } + status.hidden = false; + status.textContent = message; + status.classList.toggle("error", isError); + status.classList.toggle("success", !isError); +} + +async function loadSession() { + const response = await fetch("/api/session", { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return null; + } + const session = await response.json(); + if (!session.authenticated) { + window.location.href = "/login"; + return null; + } + if (session.is_admin !== true) { + window.location.href = "/dashboard"; + return null; + } + if (session.csrf_token) { + sessionCSRF = session.csrf_token; + } + return session; +} + +async function loadUsers() { + setStatus("Loading users..."); + list.innerHTML = ""; + const response = await fetch("/api/users", { credentials: "same-origin" }); + if (response.status === 401) { + window.location.href = "/login"; + return; + } + if (response.status === 403) { + window.location.href = "/dashboard"; + return; + } + if (!response.ok) { + setStatus("Unable to load users.", true); + return; + } + const data = await response.json(); + users = data.users || []; + renderUsers(); +} + +function renderUsers() { + if (users.length === 0) { + setStatus("No users configured."); + list.innerHTML = ""; + return; + } + + setStatus(""); + list.innerHTML = `
${users.map(renderUserCard).join("")}
`; + + list.querySelectorAll("[data-action='save-user']").forEach((button) => { + button.addEventListener("click", onSaveUser); + }); + list.querySelectorAll("[data-action='delete-user']").forEach((button) => { + button.addEventListener("click", onDeleteUser); + }); +} + +function renderUserCard(user) { + const created = user.created_at ? new Date(user.created_at).toLocaleString() : "Unknown"; + const roleOptions = ["user", "admin"] + .map((role) => ``) + .join(""); + const grants = formatPrinterGrants(user.printer_grants || []); + return ` +
+
+
+ ${escapeHTML(user.username)} +

${escapeHTML(created)}

+
+ ${escapeHTML(user.role)} +
+
+ + + +
+
+ + +
+
+ `; +} + +async function onSaveUser(event) { + const card = event.target.closest(".user-card[data-user-id]"); + if (!card) { + return; + } + const userID = card.dataset.userId; + const role = card.querySelector("[data-field='role']").value; + const password = card.querySelector("[data-field='password']").value; + try { + const grants = parsePrinterGrants(card.querySelector("[data-field='printer-grants']").value); + const payload = { role, printer_grants: grants }; + if (password) { + payload.password = password; + } + await apiRequest(`/api/users/${encodeURIComponent(userID)}`, "PATCH", payload); + setStatus("User updated."); + await loadUsers(); + } catch (error) { + setStatus(error instanceof Error ? error.message : "Unable to save user.", true); + } +} + +async function onDeleteUser(event) { + const card = event.target.closest(".user-card[data-user-id]"); + if (!card) { + return; + } + const userID = card.dataset.userId; + if (!window.confirm("Delete this user?")) { + return; + } + try { + await apiRequest(`/api/users/${encodeURIComponent(userID)}`, "DELETE"); + setStatus("User deleted."); + await loadUsers(); + } catch (error) { + setStatus(error instanceof Error ? error.message : "Unable to delete user.", true); + } +} + +async function apiRequest(url, method, body) { + const options = { + method, + credentials: "same-origin", + headers: { + "X-CSRF-Token": sessionCSRF, + }, + }; + if (body) { + options.headers["Content-Type"] = "application/json"; + options.body = JSON.stringify(body); + } + const response = await fetch(url, options); + if (!response.ok && response.status !== 204) { + const text = await response.text(); + throw new Error(text || `Request failed: ${response.status}`); + } + return response; +} + +createForm.addEventListener("submit", async (event) => { + event.preventDefault(); + const form = new FormData(createForm); + try { + const grants = parsePrinterGrants(String(form.get("printer_grants") || "")); + await apiRequest("/api/users", "POST", { + username: String(form.get("username") || ""), + password: String(form.get("password") || ""), + role: String(form.get("role") || "user"), + printer_grants: grants, + }); + createForm.reset(); + setStatus("User created."); + await loadUsers(); + } catch (error) { + setStatus(error instanceof Error ? error.message : "Unable to create user.", true); + } +}); + +refresh.addEventListener("click", loadUsers); + +function escapeHTML(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +function parsePrinterGrants(raw) { + const text = String(raw || "").trim(); + if (!text) { + return []; + } + const grants = []; + for (const line of text.split(/\r?\n/)) { + const trimmed = line.trim(); + if (!trimmed) { + continue; + } + const parts = trimmed.split(":"); + if (parts.length !== 2) { + throw new Error(`Invalid printer grant line: ${trimmed}`); + } + const printerID = parts[0].trim(); + const access = parts[1].trim().toLowerCase(); + if (!printerID) { + throw new Error("Printer grant requires a printer id."); + } + if (access !== "read" && access !== "control") { + throw new Error(`Invalid printer access for ${printerID}: ${parts[1].trim()}`); + } + grants.push({ + printer_id: printerID, + access, + }); + } + return grants; +} + +function formatPrinterGrants(grants) { + return grants + .map((grant) => `${grant.printer_id}:${grant.access || "read"}`) + .join("\n"); +} + +(async () => { + await loadSession(); + await loadUsers(); +})();