Initial Commit

This commit is contained in:
Dark98 committed 2026-05-14 02:27:26 +01:00
commit b0de8cf38c
107 files changed
+26832

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
dist/
bin/
.env
*.exe
*.log
+14
View File
@@ -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
+21
View File
@@ -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
+23
View File
@@ -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)
+86
View File
@@ -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.
+8
View File
@@ -0,0 +1,8 @@
.gradle/
build/
app/build/
.idea/
local.properties
captures/
*.iml
*.log
+42
View File
@@ -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
```
+214
View File
@@ -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")
}
}
}
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.KlipperAnywhere"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true"
android:configChanges="orientation|screenSize|keyboardHidden|smallestScreenSize|screenLayout|uiMode">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -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<PrinterSummary> = 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<PrinterSettingsView?, PrinterHealth?> = 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<UserRecord> = 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<AuditEvent> = 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<HttpCookie> = 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<Int, String> = 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<Int, String> = 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<Int, String> = 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<JSONObject> = 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<String, Any?> {
val map = linkedMapOf<String, Any?>()
keys().forEach { key ->
map[key] = toKotlinValue(opt(key))
}
return map
}
private fun JSONArray.toValueList(): List<Any?> {
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
}
}
@@ -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"
}
}
File diff suppressed because it is too large. Load diff
@@ -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<PrinterGrant>,
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<CameraInfo>,
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<String, Any?>?,
val moonrakerMetadata: Map<String, Any?>?,
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<RecentJob>,
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<PrinterGrant>,
)
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?,
)
Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ka_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ka_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

@@ -0,0 +1,6 @@
<resources>
<color name="ka_primary">#8ED7D0</color>
<color name="ka_secondary">#FFB36B</color>
<color name="ka_background">#081018</color>
<color name="ka_surface">#111A24</color>
</resources>
@@ -0,0 +1,3 @@
<resources>
<string name="app_name">KlipperAnywhere</string>
</resources>
@@ -0,0 +1,8 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<style name="Theme.KlipperAnywhere" parent="Theme.Material3.DayNight.NoActionBar">
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@color/ka_background</item>
<item name="android:windowLightStatusBar">false</item>
<item name="android:windowLightNavigationBar">false</item>
</style>
</resources>
+4
View File
@@ -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
}
+4
View File
@@ -0,0 +1,4 @@
android.useAndroidX=true
android.nonTransitiveRClass=true
kotlin.code.style=official
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
Binary file not shown.
Binary file not shown.
+7
View File
@@ -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
+23
View File
@@ -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" "$@"
+21
View File
@@ -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%
+8
View File
@@ -0,0 +1,8 @@
param(
[Parameter(ValueFromRemainingArguments = $true)]
[string[]]$Arguments
)
$batch = Join-Path $PSScriptRoot 'gradlew.bat'
& cmd /c "`"$batch`" $($Arguments -join ' ')"
exit $LASTEXITCODE
+18
View File
@@ -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")
+2351
View File
File diff suppressed because it is too large. Load diff
+452
View File
@@ -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)
}
}
+459
View File
@@ -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</title><link rel="stylesheet" href="/assets/app.css"></head><body><h1>Mock Printer UI</h1><script src="/assets/app.js"></script></body></html>`))
})
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(`<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360" viewBox="0 0 640 360"><rect width="640" height="360" fill="#111619"/><rect x="118" y="82" width="404" height="196" rx="10" fill="#1f2a2c" stroke="#48d4bf" stroke-width="4"/><circle cx="320" cy="180" r="58" fill="#48d4bf" opacity=".72"/><text x="320" y="306" fill="#f7f3eb" font-family="Arial" font-size="28" text-anchor="middle">Mock camera snapshot</text></svg>`))
}
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(`<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360" viewBox="0 0 640 360"><rect width="640" height="360" fill="#111619"/><rect x="%d" y="118" width="120" height="90" rx="8" fill="#48d4bf"/><text x="320" y="306" fill="#f7f3eb" font-family="Arial" font-size="28" text-anchor="middle">Mock camera stream %03d</text></svg>`, 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
}
+151
View File
@@ -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
}
}
+63
View File
@@ -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)
}
}
+199
View File
@@ -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
}
+545
View File
@@ -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
}
+3560
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+128
View File
@@ -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 := &notificationSettingsStore{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,
}
}
+540
View File
@@ -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, " ")
}
+540
View File
@@ -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 ""
}
}
+219
View File
@@ -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 }
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+519
View File
@@ -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
}
+142
View File
@@ -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")
}
}
+15
View File
@@ -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"
}
]
}
+8
View File
@@ -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
}
+45
View File
@@ -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
+115
View File
@@ -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.
+121
View File
@@ -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.
+88
View File
@@ -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
+110
View File
@@ -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=<session-cookie>" 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
```
+55
View File
@@ -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.
+140
View File
@@ -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.
+53
View File
@@ -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.
+38
View File
@@ -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.
+6
View File
@@ -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
+4
View File
@@ -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=
+92
View File
@@ -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"`
}
+77
View File
@@ -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
+15
View File
@@ -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
@@ -0,0 +1,6 @@
{
"$version": "1",
"name": "klipperanywhere-agent",
"description": "Runs the KlipperAnywhere tunnel agent on a Rinkhals printer host.",
"version": "0.1"
}
@@ -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 & printf "%s\n" $!' sh "$APP_ROOT" "$AGENT_BIN" "$AGENT_CFG" "$APP_LOG" 2>/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
+95
View File
@@ -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 <agent.json> [--release-base-url <url>] [--arch <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
}
+50
View File
@@ -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
+14
View File
@@ -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"
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
exec "$(dirname "$0")/install-agent.sh" "$@"
+96
View File
@@ -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 <agent-binary> <agent.json>" >&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"
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
exec "$(dirname "$0")/uninstall-agent.sh" "$@"
+35
View File
@@ -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."
+27
View File
@@ -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"
}
+15
View File
@@ -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}"
+89
View File
@@ -0,0 +1,89 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Account - KlipperAnywhere</title>
<meta name="description" content="Manage your KlipperAnywhere account.">
<meta id="csrf-meta" name="csrf-token" content="{{CSRF_TOKEN}}">
<link rel="stylesheet" href="/static/styles.css">
<link rel="icon" href="/favicon.ico">
<link rel="icon" type="image/png" href="/static/assets/favicon.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
<body class="app-page">
<header class="app-header">
<a class="brand" href="/">
<span class="brand-mark" aria-hidden="true">K</span>
<span>KlipperAnywhere</span>
</a>
<nav class="nav-links" aria-label="Account navigation">
<div class="nav-group nav-core">
<a class="text-button" href="/dashboard">Dashboard</a>
<a class="text-button current" href="/account">Account</a>
<a class="text-button admin-only" href="/admin" hidden>Admin</a>
</div>
<div class="nav-group nav-tools">
<div class="printer-switcher-group" aria-label="Printer switcher">
<label class="printer-switcher-label" for="printer-switcher">Printer</label>
<select id="printer-switcher" class="printer-switcher" aria-label="Switch printer">
<option value="">Loading printers...</option>
</select>
<button class="text-button" id="printer-switcher-open" type="button">Open</button>
</div>
<button class="text-button" id="refresh" type="button">Refresh</button>
<form class="logout-form" method="post" action="/logout">
<input type="hidden" name="csrf_token" value="{{CSRF_TOKEN}}">
<button class="text-button" type="submit">Sign out</button>
</form>
</div>
</nav>
</header>
<main class="dashboard-shell account-shell">
<section class="dashboard-heading">
<p class="eyebrow">Account settings</p>
<h1 class="dashboard-title">Account</h1>
</section>
<section class="detail-grid account-grid" aria-live="polite">
<article class="detail-panel">
<div class="panel-heading">
<h2>Profile</h2>
</div>
<dl class="printer-facts detail-facts" id="account-facts">
<div><dt>Username</dt><dd>{{USERNAME}}</dd></div>
<div><dt>Role</dt><dd>{{ROLE}}</dd></div>
</dl>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>Change password</h2>
</div>
<p class="auth-copy">Update the password for the current account.</p>
<p id="account-status" class="form-message" hidden></p>
<form id="account-form" class="user-form">
<label>
<span>Current password</span>
<input name="current_password" type="password" autocomplete="current-password" required>
</label>
<label>
<span>New password</span>
<input name="new_password" type="password" autocomplete="new-password" required>
</label>
<label>
<span>Confirm new password</span>
<input name="confirm_password" type="password" autocomplete="new-password" required>
</label>
<button class="button primary" type="submit">Update password</button>
</form>
</article>
</section>
</main>
<script src="/static/session.js"></script>
<script src="/static/printer-switcher.js"></script>
<script src="/static/account.js"></script>
</body>
</html>
+114
View File
@@ -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 = `
<div><dt>Username</dt><dd>${escapeHTML(session.username || "Unknown")}</dd></div>
<div><dt>Role</dt><dd>${escapeHTML(session.role || "user")}</dd></div>
<div><dt>Printer grants</dt><dd>${renderGrants(session.printer_grants || [])}</dd></div>
`;
}
function renderGrants(grants) {
if (!grants.length) {
return "No printer access assigned.";
}
return grants.map((grant) => `${escapeHTML(grant.printer_id)} (${escapeHTML(grant.access || "read")})`).join("<br>");
}
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("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#039;");
}
(async () => {
await loadSession();
})();
+149
View File
@@ -0,0 +1,149 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin - KlipperAnywhere</title>
<meta name="description" content="KlipperAnywhere admin settings.">
<link rel="stylesheet" href="/static/styles.css">
<link rel="icon" href="/favicon.ico">
<link rel="icon" type="image/png" href="/static/assets/favicon.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
<body class="app-page">
<header class="app-header">
<a class="brand" href="/">
<span class="brand-mark" aria-hidden="true">K</span>
<span>KlipperAnywhere</span>
</a>
<nav class="nav-links" aria-label="Admin navigation">
<div class="nav-group nav-core">
<a class="text-button" href="/dashboard">Dashboard</a>
<a class="text-button" href="/account">Account</a>
<a class="text-button current" href="/admin">Admin</a>
</div>
<div class="nav-group nav-tools">
<div class="printer-switcher-group" aria-label="Printer switcher">
<label class="printer-switcher-label" for="printer-switcher">Printer</label>
<select id="printer-switcher" class="printer-switcher" aria-label="Switch printer">
<option value="">Loading printers...</option>
</select>
<button class="text-button" id="printer-switcher-open" type="button">Open</button>
</div>
<button class="text-button" id="refresh" type="button">Refresh</button>
<form class="logout-form" method="post" action="/logout">
<input type="hidden" name="csrf_token" id="logout-csrf" value="">
<button class="text-button" type="submit">Sign out</button>
</form>
</div>
</nav>
</header>
<main class="dashboard-shell admin-shell">
<section class="dashboard-heading">
<p class="eyebrow">Administration</p>
<h1 class="dashboard-title">Admin</h1>
</section>
<section class="detail-panel admin-summary">
<div class="panel-heading">
<div>
<h2>Admin tools</h2>
<p class="panel-subtitle" id="admin-context">Manage printer installs, users, and audit history from one place.</p>
</div>
<span class="status-pill ok">Admin</span>
</div>
<div class="admin-grid">
<article class="admin-tile">
<span class="status-kicker">Printer setup</span>
<strong>Install agent</strong>
<p id="admin-install-copy">Connect to a printer host over SSH and install the agent.</p>
<div class="card-actions">
<a class="button primary" id="admin-install-link" href="/install">Open installer</a>
</div>
</article>
<article class="admin-tile">
<span class="status-kicker">Access</span>
<strong>Manage users</strong>
<p>Create accounts, set roles, and assign printer grants.</p>
<div class="card-actions">
<a class="button secondary" href="/users">Open users</a>
</div>
</article>
<article class="admin-tile">
<span class="status-kicker">Security</span>
<strong>Audit log</strong>
<p>Review recent logins, account changes, printer access, and control actions.</p>
<div class="card-actions">
<a class="button secondary" href="/audit">Open audit</a>
</div>
</article>
</div>
</section>
<section class="detail-panel admin-summary">
<div class="panel-heading">
<div>
<h2>Notifications</h2>
<p class="panel-subtitle" id="admin-notifications-summary">Configure Telegram delivery and bot commands separately.</p>
</div>
<span class="status-pill warn" id="admin-notifications-pill">Off</span>
</div>
<form class="user-form settings-form admin-notifications-form" id="admin-notifications-form">
<label class="settings-checkbox">
<input id="admin-telegram-enabled" type="checkbox">
<span>Enable Telegram delivery</span>
</label>
<label class="settings-checkbox">
<input id="admin-telegram-commands-enabled" type="checkbox">
<span>Enable Telegram bot commands</span>
</label>
<label>
<span>Telegram bot token</span>
<input id="admin-telegram-bot-token" class="inline-input" type="text" placeholder="123456:ABCDEF">
</label>
<label>
<span>Telegram chat ID</span>
<input id="admin-telegram-chat-id" class="inline-input" type="text" placeholder="123456789">
</label>
<p class="panel-subtitle">Leave the token blank to keep the saved value.</p>
<p class="panel-subtitle">The test button uses the current form values without saving them.</p>
<div class="card-actions">
<button class="button secondary" type="submit">Save Telegram settings</button>
<button class="button primary" id="admin-telegram-test" type="button">Send test notification</button>
</div>
<p class="panel-subtitle" id="admin-telegram-test-result"></p>
</form>
</section>
<section class="detail-panel admin-summary">
<div class="panel-heading">
<div>
<h2>Versions</h2>
<p class="panel-subtitle" id="admin-version-copy">Current server build and connected agent versions.</p>
</div>
<span class="status-pill ok">Version</span>
</div>
<dl class="printer-facts detail-facts admin-version-facts">
<div><dt>Server build</dt><dd id="admin-server-version">Loading...</dd></div>
<div><dt>Available agent</dt><dd id="admin-available-version">Loading...</dd></div>
</dl>
</section>
<section class="detail-panel admin-summary">
<div class="panel-heading">
<div>
<h2>Connected printers</h2>
<p class="panel-subtitle" id="admin-printers-copy">Upgrade or reinstall the agent for printers that are already connected.</p>
</div>
<span class="status-pill warn" id="admin-printer-count">0 printers</span>
</div>
<div id="admin-printers" class="admin-printer-list" aria-live="polite"></div>
</section>
</main>
<script src="/static/session.js"></script>
<script src="/static/printer-switcher.js"></script>
<script src="/static/admin.js"></script>
</body>
</html>
+329
View File
@@ -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 = `<p class="auth-copy">Unable to load printers (${response.status}).</p>`;
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 = `<p class="auth-copy">No printers are connected right now.</p>`;
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 `
<article class="admin-printer-row">
<div class="admin-printer-main">
<strong>${escapeHTML(settings.display_name || printerID || "Unknown printer")}</strong>
<p>${escapeHTML(printerID || "Unknown printer")}</p>
</div>
<dl class="admin-printer-meta">
<div><dt>Agent</dt><dd>${escapeHTML(agentVersion)}</dd></div>
<div><dt>Available</dt><dd>${escapeHTML(availableVersion)}</dd></div>
</dl>
<div class="card-actions admin-printer-actions">
<a class="button secondary" href="/printers/${encodeURIComponent(printerID)}">Open</a>
<a class="button primary" href="${upgradeLink}">${upgradeText}</a>
</div>
</article>
`;
}).join("");
} catch (error) {
adminPrinters.innerHTML = `<p class="auth-copy">Unable to load printers.</p>`;
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("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#039;");
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 937 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

+64
View File
@@ -0,0 +1,64 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Audit - KlipperAnywhere</title>
<meta name="description" content="Audit log for KlipperAnywhere actions.">
<meta id="csrf-meta" name="csrf-token" content="{{CSRF_TOKEN}}">
<link rel="stylesheet" href="/static/styles.css">
<link rel="icon" href="/favicon.ico">
<link rel="icon" type="image/png" href="/static/assets/favicon.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
<body class="app-page">
<header class="app-header">
<a class="brand" href="/">
<span class="brand-mark" aria-hidden="true">K</span>
<span>KlipperAnywhere</span>
</a>
<nav class="nav-links" aria-label="Audit navigation">
<div class="nav-group nav-core">
<a class="text-button" href="/dashboard">Dashboard</a>
<a class="text-button" href="/account">Account</a>
<a class="text-button admin-only" href="/admin" hidden>Admin</a>
</div>
<div class="nav-group nav-tools">
<div class="printer-switcher-group" aria-label="Printer switcher">
<label class="printer-switcher-label" for="printer-switcher">Printer</label>
<select id="printer-switcher" class="printer-switcher" aria-label="Switch printer">
<option value="">Loading printers...</option>
</select>
<button class="text-button" id="printer-switcher-open" type="button">Open</button>
</div>
<button class="text-button" id="refresh" type="button">Refresh</button>
<form class="logout-form" method="post" action="/logout">
<input type="hidden" name="csrf_token" value="{{CSRF_TOKEN}}">
<button class="text-button" type="submit">Sign out</button>
</form>
</div>
</nav>
</header>
<main class="dashboard-shell audit-shell">
<section class="dashboard-heading">
<p class="eyebrow">Security trail</p>
<h1 class="dashboard-title">Audit log</h1>
</section>
<section class="detail-panel audit-panel">
<div class="panel-heading">
<h2>Recent events</h2>
<a href="/api/audit?limit=100" id="audit-json-link">JSON</a>
</div>
<p id="audit-status" class="empty-state">Loading audit events...</p>
<div id="audit-list" class="audit-list"></div>
</section>
</main>
<script src="/static/session.js"></script>
<script src="/static/printer-switcher.js"></script>
<script src="/static/session.js"></script>
<script src="/static/audit.js"></script>
</body>
</html>
+78
View File
@@ -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 ? `<strong>${escapeHTML(event.actor)}</strong>` : "<strong>system</strong>",
`<span class="audit-action">${escapeHTML(event.action || "event")}</span>`,
event.printer_id ? `<span>${escapeHTML(event.printer_id)}</span>` : "",
event.target_id ? `<span>${escapeHTML(event.target_id)}</span>` : "",
event.method ? `<span>${escapeHTML(event.method)}</span>` : "",
event.path ? `<span>${escapeHTML(event.path)}</span>` : "",
].filter(Boolean);
return `
<article class="audit-event">
<div class="audit-event-top">
<span class="audit-time">${escapeHTML(timestamp)}</span>
<span class="status-pill warn">${escapeHTML(event.action || "event")}</span>
</div>
<div class="audit-event-body">
${parts.join("")}
</div>
${event.detail ? `<p class="audit-detail">${escapeHTML(event.detail)}</p>` : ""}
${event.status ? `<p class="audit-detail">Status ${escapeHTML(String(event.status))}</p>` : ""}
</article>
`;
}
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("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#039;");
}
refresh.addEventListener("click", loadAudit);
loadAudit();
+57
View File
@@ -0,0 +1,57 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dashboard - KlipperAnywhere</title>
<meta name="description" content="KlipperAnywhere printer dashboard.">
<link rel="stylesheet" href="/static/styles.css">
<link rel="icon" href="/favicon.ico">
<link rel="icon" type="image/png" href="/static/assets/favicon.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
<body class="app-page">
<header class="app-header">
<a class="brand" href="/">
<span class="brand-mark" aria-hidden="true">K</span>
<span>KlipperAnywhere</span>
</a>
<nav class="nav-links" aria-label="Dashboard navigation">
<div class="nav-group nav-core">
<a class="text-button current" href="/dashboard">Dashboard</a>
<a class="text-button" href="/account">Account</a>
<a class="text-button admin-only" href="/admin" hidden>Admin</a>
</div>
<div class="nav-group nav-tools">
<div class="printer-switcher-group" aria-label="Printer switcher">
<label class="printer-switcher-label" for="printer-switcher">Printer</label>
<select id="printer-switcher" class="printer-switcher" aria-label="Switch printer">
<option value="">Loading printers...</option>
</select>
<button class="text-button" id="printer-switcher-open" type="button">Open</button>
</div>
<button class="text-button" id="refresh" type="button">Refresh</button>
<form class="logout-form" method="post" action="/logout">
<input type="hidden" name="csrf_token" value="{{CSRF_TOKEN}}">
<button class="text-button" type="submit">Sign out</button>
</form>
</div>
</nav>
</header>
<main class="dashboard-shell">
<section class="dashboard-heading">
<p class="eyebrow">Connected printers</p>
<h1 class="dashboard-title">Dashboard</h1>
</section>
<section class="printer-grid" id="printer-grid" aria-live="polite">
<p class="empty-state">Loading printers...</p>
</section>
</main>
<script src="/static/session.js"></script>
<script src="/static/printer-switcher.js"></script>
<script src="/static/dashboard.js"></script>
</body>
</html>
+309
View File
@@ -0,0 +1,309 @@
const grid = document.getElementById("printer-grid");
const refresh = document.getElementById("refresh");
async function loadPrinters() {
grid.innerHTML = '<p class="empty-state">Loading printers...</p>';
const response = await fetch("/api/printers", { credentials: "same-origin" });
if (response.status === 401) {
window.location.href = "/login";
return;
}
if (!response.ok) {
grid.innerHTML = '<p class="empty-state">Unable to load printers.</p>';
return;
}
const data = await response.json();
const printers = data.printers || [];
if (printers.length === 0) {
grid.innerHTML = '<p class="empty-state">No agents are connected.</p>';
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
? `<img class="printer-thumb" src="/p/${encodeURIComponent(printer.printer_id)}/camera/${encodeURIComponent(camera.name)}/snapshot?t=${Date.now()}" alt="${escapeHTML(printer.printer_id)} camera snapshot">`
: '<div class="printer-thumb printer-thumb-empty">No camera</div>';
return `
<article class="printer-card ${reachable ? "healthy" : "unhealthy"}">
${thumbnail}
<div class="printer-card-header">
<div>
<span class="status-pill ${reachable ? "ok" : "warn"}">${reachable ? "Reachable" : "Not reachable"}</span>
<h2>${escapeHTML(label)}</h2>
${label !== printer.printer_id ? `<p class="panel-subtitle">${escapeHTML(printer.printer_id)}</p>` : ""}
</div>
</div>
<dl class="printer-facts">
<div>
<dt>Agent</dt>
<dd>${printer.connected ? "Connected" : "Disconnected"}</dd>
</div>
<div>
<dt>Moonraker</dt>
<dd>${escapeHTML(state)}</dd>
</div>
<div>
<dt>Message</dt>
<dd>${escapeHTML(message)}</dd>
</div>
<div>
<dt>Last heartbeat</dt>
<dd>${escapeHTML(checked)}</dd>
</div>
${temperatureSummary ? `
<div>
<dt>Temps</dt>
<dd class="temperature-summary">${escapeHTML(temperatureSummary)}</dd>
</div>` : ""}
${mmuMaterials ? `
<div>
<dt>MMU materials</dt>
<dd class="mmu-materials-value">${mmuMaterials}</dd>
</div>` : ""}
</dl>
<div class="card-actions">
<a class="button primary" href="/printers/${encodeURIComponent(printer.printer_id)}">Open</a>
${session.is_admin ? `<a class="button secondary" href="/printers/${encodeURIComponent(printer.printer_id)}/settings">Settings</a>` : ""}
<a class="button secondary ${uiReachable ? "" : "disabled"}" href="${uiReachable ? `/printers/${encodeURIComponent(printer.printer_id)}/ui/` : "#"}" ${uiReachable ? "" : 'aria-disabled="true"'}>${uiReachable ? "Open Printer UI" : "UI unavailable"}</a>
<a class="button secondary" href="/api/printers/${encodeURIComponent(printer.printer_id)}/health">Health JSON</a>
<a class="button secondary" href="/p/${encodeURIComponent(printer.printer_id)}/moonraker/printer/info">Printer Info</a>
</div>
</article>
`;
}
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("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#039;");
}
function formatMmuMaterialsHtml(printStatus) {
if (!printStatus || typeof printStatus !== "object") {
return "";
}
const state = collectMmuMaterialState(printStatus);
if (!state.visible) {
return "";
}
if (state.disabled) {
return `<span class="mmu-material-chip mmu-disabled"><span class="mmu-material-chip-swatch"></span><span class="mmu-material-chip-text">${escapeHTML(state.label)}: disabled</span></span>`;
}
if (state.rows.length === 0) {
return `<span class="mmu-material-chip"><span class="mmu-material-chip-swatch"></span><span class="mmu-material-chip-text">${escapeHTML(state.label)}: enabled</span></span>`;
}
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 `<span class="mmu-material-chip"${swatchStyle}><span class="mmu-material-chip-swatch"></span><span class="mmu-material-chip-text"><strong>${label}</strong>${value ? ` ${value}` : ""}</span></span>`;
}
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);
});
+70
View File
@@ -0,0 +1,70 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>KlipperAnywhere</title>
<meta name="description" content="Self-hosted remote access for Klipper printers.">
<link rel="stylesheet" href="/static/styles.css">
<link rel="icon" href="/favicon.ico">
<link rel="icon" type="image/png" href="/static/assets/favicon.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
<body>
<header class="site-header" aria-label="Primary">
<a class="brand" href="/">
<span class="brand-mark" aria-hidden="true">K</span>
<span>KlipperAnywhere</span>
</a>
<nav class="nav-links" id="main-nav" aria-label="Main navigation">
<a class="auth-link logged-in-only" href="/dashboard" hidden>Dashboard</a>
<a class="auth-link logged-in-only" href="/account" hidden>Account</a>
<a class="auth-link admin-only logged-in-only" href="/admin" hidden>Admin</a>
<a class="auth-link logged-out-only" href="/login">Sign in</a>
<form class="logout-form logged-in-only" id="landing-logout" method="post" action="/logout" hidden>
<input id="landing-csrf" type="hidden" name="csrf_token" value="">
<button class="text-button" type="submit">Sign out</button>
</form>
<a href="https://github.com/" rel="noreferrer">GitHub</a>
</nav>
</header>
<main>
<section class="hero">
<img class="hero-image" src="/static/assets/hero-printer.png" alt="A modern 3D printer in a tidy workshop with a remote monitoring dashboard nearby.">
<div class="hero-shade" aria-hidden="true"></div>
<div class="hero-content">
<p class="eyebrow">Open-source remote access for Klipper</p>
<h1>KlipperAnywhere</h1>
<p class="lede">A self-hosted tunnel for Moonraker, printer UIs, and camera access without opening inbound ports on your printer network.</p>
<div class="actions" aria-label="Primary actions">
<a class="button primary logged-in-only" href="/dashboard" hidden>Open Dashboard</a>
<a class="button secondary logged-in-only" href="/account" hidden>Account</a>
<a class="button secondary admin-only logged-in-only" href="/admin" hidden>Admin</a>
<a class="button primary logged-out-only" href="/login">Sign in</a>
<a class="button secondary" href="https://github.com/" rel="noreferrer">View Source</a>
</div>
</div>
</section>
<section class="status-band" aria-label="Current project status">
<div class="status-item">
<span class="status-kicker">Tunnel</span>
<strong>Outbound agent</strong>
<p>Printer-side connection over WebSocket.</p>
</div>
<div class="status-item">
<span class="status-kicker">Target</span>
<strong>Moonraker first</strong>
<p>HTTP proxying and health heartbeats are in place.</p>
</div>
<div class="status-item">
<span class="status-kicker">Install</span>
<strong>Small Go binary</strong>
<p>Designed for Raspberry Pi and rooted printer hosts.</p>
</div>
</section>
</main>
<script src="/static/session.js"></script>
</body>
</html>
+124
View File
@@ -0,0 +1,124 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Install Printer - KlipperAnywhere</title>
<meta name="description" content="Install the KlipperAnywhere agent on a printer over SSH.">
<meta id="csrf-meta" name="csrf-token" content="{{CSRF_TOKEN}}">
<link rel="stylesheet" href="/static/styles.css">
<link rel="icon" href="/favicon.ico">
<link rel="icon" type="image/png" href="/static/assets/favicon.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
<body class="app-page">
<header class="app-header">
<a class="brand" href="/">
<span class="brand-mark" aria-hidden="true">K</span>
<span>KlipperAnywhere</span>
</a>
<nav class="nav-links" aria-label="Install navigation">
<div class="nav-group nav-core">
<a class="text-button" href="/dashboard">Dashboard</a>
<a class="text-button" href="/account">Account</a>
<a class="text-button admin-only" href="/admin" hidden>Admin</a>
</div>
<div class="nav-group nav-tools">
<div class="printer-switcher-group" aria-label="Printer switcher">
<label class="printer-switcher-label" for="printer-switcher">Printer</label>
<select id="printer-switcher" class="printer-switcher" aria-label="Switch printer">
<option value="">Loading printers...</option>
</select>
<button class="text-button" id="printer-switcher-open" type="button">Open</button>
</div>
<button class="text-button" id="refresh" type="button">Refresh</button>
<form class="logout-form" method="post" action="/logout">
<input type="hidden" name="csrf_token" value="{{CSRF_TOKEN}}">
<button class="text-button" type="submit">Sign out</button>
</form>
</div>
</nav>
</header>
<main class="dashboard-shell install-shell">
<section class="dashboard-heading">
<p class="eyebrow">Printer setup</p>
<h1 class="dashboard-title">Install agent over SSH</h1>
</section>
<section class="detail-grid install-grid" aria-live="polite">
<article class="detail-panel">
<div class="panel-heading">
<h2>Connection</h2>
</div>
<p class="auth-copy">Connect to the printer host, upload the installer, and start the agent without touching the host manually.</p>
<p class="auth-copy install-note">Use a root account or a user with passwordless sudo. If you opened this from a printer page, the printer ID will prefill.</p>
<p id="install-status" class="form-message" hidden></p>
<form id="install-form" class="user-form install-form">
<label>
<span>Printer host / IP</span>
<input name="host" autocomplete="off" placeholder="192.168.1.60" required>
</label>
<label>
<span>Server URL</span>
<input name="server_url" autocomplete="off" placeholder="https://klipperanywhere.example.com">
</label>
<p class="panel-subtitle">Use the URL the printer can reach from its own network, not <code>127.0.0.1</code> or <code>localhost</code>.</p>
<label>
<span>SSH port</span>
<input name="port" type="number" min="1" max="65535" value="22">
</label>
<label>
<span>SSH username</span>
<input name="username" autocomplete="username" required>
</label>
<label>
<span>SSH password</span>
<input name="password" type="password" autocomplete="current-password" required>
</label>
<label>
<span>Printer ID</span>
<input name="printer_id" autocomplete="off" placeholder="Optional, defaults to the remote hostname">
</label>
<label>
<span>Printer host type</span>
<select name="host_type" class="settings-select">
<option value="standard">Standard Linux service</option>
<option value="rinkhals">Rinkhals app</option>
</select>
</label>
<p class="panel-subtitle">Choose Rinkhals only if the printer host runs the Rinkhals app framework. Standard installs use a service or init script.</p>
<label>
<span>Moonraker URL</span>
<input name="moonraker_url" autocomplete="off" placeholder="http://127.0.0.1:7125" value="http://127.0.0.1:7125">
</label>
<label>
<span>UI URL</span>
<input name="ui_url" autocomplete="off" placeholder="Optional, defaults to auto-detect">
</label>
<label class="settings-checkbox">
<input name="ui_auto_detect" type="checkbox" checked>
<span>Auto-detect the printer UI on the host</span>
</label>
<button class="button primary" type="submit">Install agent</button>
</form>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>Result</h2>
</div>
<p class="auth-copy">The installer uploads the bootstrap scripts, generates the agent config, and runs the remote setup flow.</p>
<dl class="printer-facts detail-facts" id="install-facts">
<div><dt>Status</dt><dd>Waiting</dd></div>
</dl>
<pre class="install-output" id="install-output">No install has been run yet.</pre>
</article>
</section>
</main>
<script src="/static/session.js"></script>
<script src="/static/printer-switcher.js"></script>
<script src="/static/install.js"></script>
</body>
</html>
+419
View File
@@ -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 = `<div><dt>Status</dt><dd>Installing</dd></div>`;
}
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 = `<div><dt>Status</dt><dd>Failed</dd></div>`;
}
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 = `<div><dt>Status</dt><dd>Failed</dd></div>`;
}
}
}
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 `<div><dt>${escapeHTML(label)}</dt><dd>${escapeHTML(value)}</dd></div>`;
}
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("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#039;");
}
refresh.addEventListener("click", () => window.location.reload());
form.addEventListener("submit", runInstall);
loadSession().then(() => preloadInstallDetails());
+46
View File
@@ -0,0 +1,46 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sign in - KlipperAnywhere</title>
<meta name="description" content="Sign in to KlipperAnywhere.">
<link rel="stylesheet" href="/static/styles.css">
<link rel="icon" href="/favicon.ico">
<link rel="icon" type="image/png" href="/static/assets/favicon.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
<body class="auth-page">
<main class="auth-shell">
<a class="brand auth-brand" href="/">
<span class="brand-mark" aria-hidden="true">K</span>
<span>KlipperAnywhere</span>
</a>
<section class="auth-panel" aria-labelledby="login-title">
<p class="eyebrow">Private access</p>
<h1 id="login-title" class="auth-title">Sign in</h1>
<p class="auth-copy">Access connected printers, health checks, and proxied Moonraker endpoints.</p>
<p class="form-error" id="form-error" hidden>Invalid username or password.</p>
<form class="login-form" method="post" action="/login">
<label>
<span>Username</span>
<input name="username" autocomplete="username" required>
</label>
<label>
<span>Password</span>
<input name="password" type="password" autocomplete="current-password" required>
</label>
<button class="button primary" type="submit">Sign in</button>
</form>
</section>
</main>
<script>
if (new URLSearchParams(window.location.search).has("error")) {
document.getElementById("form-error").hidden = false;
}
</script>
</body>
</html>
+188
View File
@@ -0,0 +1,188 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Agent - KlipperAnywhere</title>
<meta name="description" content="KlipperAnywhere printer agent health view.">
<link rel="stylesheet" href="/static/styles.css">
<link rel="icon" href="/favicon.ico">
<link rel="icon" type="image/png" href="/static/assets/favicon.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
<body class="app-page">
<header class="app-header">
<a class="brand" href="/">
<span class="brand-mark" aria-hidden="true">K</span>
<span>KlipperAnywhere</span>
</a>
<nav class="nav-links" aria-label="Printer agent navigation">
<div class="nav-group nav-core">
<a href="/dashboard">Dashboard</a>
<a id="back-link" href="#">Printer</a>
<a class="current" href="#" aria-current="page">Agent</a>
<a id="settings-link" href="#">Settings</a>
<a id="ui-link" href="#">Open Printer UI</a>
<a class="admin-only" id="admin-link" href="/admin" hidden>Admin</a>
</div>
<div class="nav-group nav-tools">
<div class="printer-switcher-group" aria-label="Printer switcher">
<label class="printer-switcher-label" for="printer-switcher">Printer</label>
<select id="printer-switcher" class="printer-switcher" aria-label="Switch printer">
<option value="">Loading printers...</option>
</select>
<button class="text-button" id="printer-switcher-open" type="button">Open</button>
</div>
<button class="text-button" id="refresh" type="button">Refresh</button>
<form class="logout-form" method="post" action="/logout">
<input type="hidden" name="csrf_token" id="logout-csrf" value="">
<button class="text-button" type="submit">Sign out</button>
</form>
</div>
</nav>
</header>
<main class="dashboard-shell printer-detail-shell">
<section class="detail-hero">
<div>
<p class="eyebrow">Printer agent</p>
<h1 class="dashboard-title" id="printer-title">Loading...</h1>
</div>
<span class="status-pill warn" id="printer-status">Checking</span>
</section>
<section class="detail-grid" aria-live="polite">
<article class="detail-panel">
<div class="panel-heading">
<h2>Agent</h2>
<a id="health-link" href="#">JSON</a>
</div>
<dl class="printer-facts detail-facts" id="agent-facts">
<div><dt>Agent</dt><dd>Loading...</dd></div>
</dl>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>Connectivity</h2>
</div>
<dl class="printer-facts detail-facts" id="connectivity-facts">
<div><dt>Moonraker</dt><dd>Loading...</dd></div>
</dl>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>UI</h2>
</div>
<dl class="printer-facts detail-facts" id="ui-facts">
<div><dt>UI</dt><dd>Loading...</dd></div>
</dl>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>Settings Sync</h2>
<a id="settings-edit-link" href="#">Edit</a>
</div>
<p class="panel-subtitle" id="sync-summary">Waiting for printer heartbeat.</p>
<dl class="printer-facts detail-facts" id="sync-facts">
<div><dt>Control mode</dt><dd>Loading...</dd></div>
</dl>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>Install Details</h2>
<a id="install-link" href="#">Install</a>
</div>
<p class="panel-subtitle" id="install-summary">No install details saved yet.</p>
<p class="panel-subtitle" id="install-version-summary">Checking update status...</p>
<p class="form-message" id="install-message" hidden></p>
<dl class="printer-facts detail-facts" id="install-facts">
<div><dt>Status</dt><dd>Waiting...</dd></div>
</dl>
<div class="panel-actions">
<button class="button secondary" id="update-check" type="button">Check for updates</button>
<button class="button primary" id="upgrade-now" type="button">Upgrade now</button>
<a class="button secondary" id="install-action" href="#">Reinstall via SSH</a>
</div>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>Rinkhals App</h2>
<a id="rinkhals-link" href="#">Raw</a>
</div>
<p class="panel-subtitle" id="rinkhals-summary">Not using the Rinkhals app runtime.</p>
<dl class="printer-facts detail-facts" id="rinkhals-facts">
<div><dt>Runtime</dt><dd>Not applicable</dd></div>
</dl>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>Install History</h2>
<a id="install-history-link" href="#">Raw</a>
</div>
<div id="install-history-list" class="recent-jobs-list">
<p class="empty-state">No install history saved yet.</p>
</div>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>Print Status</h2>
<a id="print-status-link" href="#">Raw</a>
</div>
<dl class="printer-facts detail-facts" id="print-status-facts">
<div><dt>State</dt><dd>Loading...</dd></div>
</dl>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>Raw Moonraker</h2>
<a id="moonraker-raw-link" href="#">Raw</a>
</div>
<p class="panel-subtitle" id="moonraker-raw-summary">Waiting for printer data.</p>
<dl class="printer-facts detail-facts" id="moonraker-raw-facts">
<div><dt>Raw keys</dt><dd>Waiting...</dd></div>
</dl>
<pre class="raw-json" id="moonraker-raw-json">Waiting for Moonraker status...</pre>
</article>
<article class="detail-panel">
<div class="panel-heading">
<h2>Cameras</h2>
<a id="camera-link" href="#">Raw</a>
</div>
<div id="camera-list" class="recent-jobs-list">
<p class="empty-state">Waiting for camera configuration...</p>
</div>
</article>
</section>
</main>
<div class="modal-backdrop" id="ssh-password-modal" hidden>
<section class="modal-card" role="dialog" aria-modal="true" aria-labelledby="ssh-password-title">
<div class="panel-heading">
<h2 id="ssh-password-title">SSH password required</h2>
</div>
<p class="panel-subtitle">Enter the printer host password to continue with the reinstall flow. It is only stored in this browser session.</p>
<label class="modal-field">
<span>SSH password</span>
<input id="ssh-password-input" type="password" autocomplete="current-password">
</label>
<div class="modal-actions">
<button class="button secondary" id="ssh-password-cancel" type="button">Cancel</button>
<button class="button primary" id="ssh-password-continue" type="button">Continue</button>
</div>
</section>
</div>
<script src="/static/session.js"></script>
<script src="/static/printer-switcher.js"></script>
<script src="/static/printer-agent.js"></script>
</body>
</html>
+807
View File
@@ -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 = '<p class="empty-state">No install history saved yet.</p>';
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 `
<section class="job-row">
<div class="job-row-top">
<strong>${escapeHTML(entry.updated_at ? new Date(entry.updated_at).toLocaleString() : "Unknown time")}</strong>
<span class="status-pill ${statusClass}">${escapeHTML(statusLabel)}</span>
</div>
<p class="panel-subtitle">${escapeHTML(summary)}</p>
<dl class="printer-facts job-facts">
<div><dt>Host</dt><dd>${escapeHTML(`${entry.host || "Unknown"}:${entry.port || 22}`)}</dd></div>
<div><dt>Username</dt><dd>${escapeHTML(entry.username || "Unknown")}</dd></div>
<div><dt>Version</dt><dd>${escapeHTML(entry.status === "installed" ? versionState.current : "Unknown")}</dd></div>
<div><dt>Context</dt><dd>${escapeHTML(context.join(" / ") || "No extra details")}</dd></div>
</dl>
</section>
`;
}).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 = '<p class="empty-state">No cameras are configured for this agent.</p>';
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 `
<section class="job-row">
<div class="job-row-top">
<strong>${escapeHTML(camera.name || "Camera")}</strong>
<span class="status-pill ${camera.has_stream ? "ok" : "warn"}">${camera.has_stream ? "stream" : "snapshot"}</span>
</div>
<dl class="printer-facts job-facts">
<div><dt>Source</dt><dd>${escapeHTML(previewBits.join(" / ") || "Configured camera")}</dd></div>
<div><dt>Snapshot</dt><dd>${camera.has_snapshot ? `<a href="${snapshotURL}" target="_blank" rel="noreferrer">Open</a>` : "Unavailable"}</dd></div>
<div><dt>Stream</dt><dd>${camera.has_stream ? `<a href="${streamURL}" target="_blank" rel="noreferrer">Open</a>` : "Unavailable"}</dd></div>
<div><dt>Aspect</dt><dd>${escapeHTML(camera.aspect_ratio || "16:9")}</dd></div>
</dl>
</section>
`;
}).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 `<div><dt>${escapeHTML(label)}</dt><dd>${escapeHTML(value)}</dd></div>`;
}
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("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#039;");
}
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);
+165
View File
@@ -0,0 +1,165 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Printer Settings - KlipperAnywhere</title>
<meta name="description" content="KlipperAnywhere printer settings.">
<link rel="stylesheet" href="/static/styles.css">
<link rel="icon" href="/favicon.ico">
<link rel="icon" type="image/png" href="/static/assets/favicon.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
<body class="app-page">
<header class="app-header">
<a class="brand" href="/">
<span class="brand-mark" aria-hidden="true">K</span>
<span>KlipperAnywhere</span>
</a>
<nav class="nav-links" aria-label="Printer settings navigation">
<div class="nav-group nav-core">
<a href="/dashboard">Dashboard</a>
<a id="back-link" href="#">Printer</a>
<a id="agent-link" href="#">Agent</a>
<a id="ui-link" href="#">Open Printer UI</a>
<a class="admin-only" id="admin-link" href="/admin" hidden>Admin</a>
</div>
<div class="nav-group nav-tools">
<div class="printer-switcher-group" aria-label="Printer switcher">
<label class="printer-switcher-label" for="printer-switcher">Printer</label>
<select id="printer-switcher" class="printer-switcher" aria-label="Switch printer">
<option value="">Loading printers...</option>
</select>
<button class="text-button" id="printer-switcher-open" type="button">Open</button>
</div>
<button class="text-button" id="refresh" type="button">Refresh</button>
<form class="logout-form" method="post" action="/logout">
<input type="hidden" name="csrf_token" id="logout-csrf" value="">
<button class="text-button" type="submit">Sign out</button>
</form>
</div>
</nav>
</header>
<main class="dashboard-shell printer-detail-shell">
<section class="detail-hero">
<div>
<p class="eyebrow">Printer settings</p>
<h1 class="dashboard-title" id="printer-title">Loading...</h1>
</div>
<span class="status-pill warn" id="printer-status">Checking</span>
</section>
<section class="detail-grid" aria-live="polite">
<article class="detail-panel">
<div class="panel-heading">
<h2>Identity</h2>
<a id="printer-open-link" href="#">Open</a>
</div>
<dl class="printer-facts detail-facts" id="identity-facts">
<div><dt>Printer</dt><dd>Loading...</dd></div>
</dl>
</article>
<article class="detail-panel">
<div class="panel-heading">
<div>
<h2>Editable settings</h2>
<p class="panel-subtitle" id="settings-summary">Waiting for printer heartbeat.</p>
</div>
<span class="status-pill warn" id="settings-sync-pill">Pending</span>
</div>
<p class="auth-copy">Rename the printer for the UI and keep the agent sync settings in one place.</p>
<p class="form-message" id="settings-message" hidden></p>
<form class="user-form settings-form" id="printer-settings-form">
<label>
<span>Display name</span>
<input id="settings-display-name" class="inline-input" type="text" placeholder="Living room printer">
</label>
<label>
<span>Control mode</span>
<select id="settings-control-mode" class="inline-select settings-select">
<option value="readonly">Readonly</option>
<option value="full">Control</option>
</select>
</label>
<label>
<span>UI URL</span>
<input id="settings-ui-url" class="inline-input" type="url" placeholder="http://192.168.1.60">
</label>
<label class="settings-checkbox">
<input id="settings-ui-auto-detect" type="checkbox">
<span>Auto-detect UI on the printer host</span>
</label>
<button class="button primary" type="submit">Save settings</button>
</form>
<section class="settings-applied" aria-live="polite">
<div class="panel-heading settings-applied-heading">
<div>
<h3>Print notifications</h3>
<p class="panel-subtitle" id="notifications-summary">No notification types configured yet.</p>
</div>
<div class="panel-heading-inline">
<span class="status-pill warn" id="notifications-pill">Off</span>
</div>
</div>
<form class="user-form settings-form" id="printer-notifications-form">
<label class="settings-checkbox">
<input id="settings-notifications-enabled" type="checkbox">
<span>Enable print notifications</span>
</label>
<div class="settings-checklist">
<label class="settings-checkbox"><input id="settings-notify-started" type="checkbox"><span>Print started</span></label>
<label class="settings-checkbox"><input id="settings-notify-paused" type="checkbox"><span>Print paused</span></label>
<label class="settings-checkbox"><input id="settings-notify-resumed" type="checkbox"><span>Print resumed</span></label>
<label class="settings-checkbox"><input id="settings-notify-completed" type="checkbox"><span>Print completed</span></label>
<label class="settings-checkbox"><input id="settings-notify-canceled" type="checkbox"><span>Print canceled</span></label>
<label class="settings-checkbox"><input id="settings-notify-failed" type="checkbox"><span>Print failed</span></label>
</div>
<div class="settings-checklist settings-subgroup">
<label class="settings-checkbox"><input id="settings-notify-first-layer" type="checkbox"><span>First layer completed</span></label>
<label class="settings-checkbox"><input id="settings-notify-third-layer" type="checkbox"><span>Third layer completed</span></label>
</div>
<label>
<span>Snapshot camera</span>
<select id="settings-notification-snapshot-camera" class="inline-select settings-select">
<option value="">First snapshot-capable camera</option>
</select>
</label>
<p class="panel-subtitle">These toggles control which print events this printer emits. Telegram delivery is configured globally from Admin.</p>
<button class="button secondary" type="submit">Save notification settings</button>
</form>
</section>
<section class="settings-applied" aria-live="polite">
<div class="panel-heading settings-applied-heading">
<div>
<h3>Agent applied</h3>
<p class="panel-subtitle" id="settings-applied-summary">Waiting for printer heartbeat.</p>
</div>
<div class="panel-heading-inline">
<span class="status-pill warn" id="settings-applied-pill">Pending</span>
<a class="panel-heading-link" id="settings-upgrade-link" href="/install">Upgrade agent</a>
</div>
</div>
<dl class="printer-facts detail-facts settings-applied-facts" id="settings-applied-facts">
<div><dt>Applied mode</dt><dd>Waiting...</dd></div>
<div><dt>Applied UI URL</dt><dd>Waiting...</dd></div>
<div><dt>UI source</dt><dd>Waiting...</dd></div>
<div><dt>UI reachable</dt><dd>Waiting...</dd></div>
<div><dt>Moonraker</dt><dd>Waiting...</dd></div>
<div><dt>Last heartbeat</dt><dd>Waiting...</dd></div>
<div><dt>Current agent</dt><dd>Waiting...</dd></div>
<div><dt>Available agent</dt><dd>Waiting...</dd></div>
</dl>
</section>
</article>
</section>
</main>
<script src="/static/session.js"></script>
<script src="/static/printer-switcher.js"></script>
<script src="/static/printer-settings.js"></script>
</body>
</html>
+435
View File
@@ -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 = ['<option value="">First snapshot-capable camera</option>'];
let hasSelected = selected === "";
snapshotCameras.forEach((camera) => {
const name = String(camera.name || "").trim();
if (name === selected) {
hasSelected = true;
}
options.push(`<option value="${escapeHTML(name)}">${escapeHTML(name)}</option>`);
});
if (selected && !hasSelected) {
options.push(`<option value="${escapeHTML(selected)}">${escapeHTML(selected)} (unavailable)</option>`);
}
settingsNotificationSnapshotCamera.innerHTML = options.join("");
settingsNotificationSnapshotCamera.value = selected;
settingsNotificationSnapshotCamera.disabled = snapshotCameras.length === 0 && selected === "";
}
function fact(label, value) {
return `<div><dt>${escapeHTML(label)}</dt><dd>${escapeHTML(value)}</dd></div>`;
}
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("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#039;");
}
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);
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more