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 "" } }