1777 lines
58 KiB
Go
1777 lines
58 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"net/url"
|
|
"path"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/klipperanywhere/klipperanywhere/internal/protocol"
|
|
)
|
|
|
|
type telegramBot struct {
|
|
client *http.Client
|
|
settings *notificationSettingsStore
|
|
server *server
|
|
mu sync.Mutex
|
|
menuMu sync.Mutex
|
|
menuState string
|
|
selections map[string]telegramPrintSelection
|
|
cameraSelections map[string]telegramCameraSelection
|
|
temperatureSelections map[string]telegramTemperatureSelection
|
|
}
|
|
|
|
type telegramUpdate struct {
|
|
UpdateID int64 `json:"update_id"`
|
|
Message *telegramMessage `json:"message,omitempty"`
|
|
CallbackQuery *telegramCallbackQuery `json:"callback_query,omitempty"`
|
|
}
|
|
|
|
type telegramMessage struct {
|
|
MessageID int64 `json:"message_id"`
|
|
Chat telegramChat `json:"chat"`
|
|
Text string `json:"text,omitempty"`
|
|
}
|
|
|
|
type telegramChat struct {
|
|
ID int64 `json:"id"`
|
|
}
|
|
|
|
type telegramCallbackQuery struct {
|
|
ID string `json:"id"`
|
|
From telegramUser `json:"from"`
|
|
Data string `json:"data,omitempty"`
|
|
Message *telegramMessage `json:"message,omitempty"`
|
|
}
|
|
|
|
type telegramUser struct {
|
|
ID int64 `json:"id"`
|
|
}
|
|
|
|
type telegramPrintSelection struct {
|
|
PrinterID string
|
|
Filename string
|
|
Label string
|
|
CreatedAt time.Time
|
|
}
|
|
|
|
type telegramCameraSelection struct {
|
|
PrinterID string
|
|
CameraName string
|
|
CreatedAt time.Time
|
|
}
|
|
|
|
type telegramTemperatureSelection struct {
|
|
PrinterID string
|
|
Heater string
|
|
Target float64
|
|
CreatedAt time.Time
|
|
}
|
|
|
|
type telegramPrintableJob struct {
|
|
Filename string
|
|
Label string
|
|
ButtonLabel string
|
|
}
|
|
|
|
type telegramCallbackAction struct {
|
|
Kind string
|
|
ID string
|
|
}
|
|
|
|
func (b *telegramBot) run(ctx context.Context) {
|
|
if b == nil || b.client == nil || b.settings == nil || b.server == nil {
|
|
return
|
|
}
|
|
offset := int64(0)
|
|
backoff := 5 * time.Second
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
default:
|
|
}
|
|
|
|
enabled, token, chatID := b.commandCredentials()
|
|
if !enabled || token == "" || chatID == "" {
|
|
if err := b.syncCommandMenu(ctx, token, false, false); err != nil {
|
|
log.Printf("telegram bot command menu update failed: %v", err)
|
|
}
|
|
select {
|
|
case <-time.After(10 * time.Second):
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
continue
|
|
}
|
|
if err := b.syncCommandMenu(ctx, token, true, true); err != nil {
|
|
log.Printf("telegram bot command menu update failed: %v", err)
|
|
}
|
|
|
|
updates, err := b.fetchUpdates(ctx, token, offset)
|
|
if err != nil {
|
|
log.Printf("telegram bot polling failed: %v", err)
|
|
select {
|
|
case <-time.After(backoff):
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
if backoff < 30*time.Second {
|
|
backoff *= 2
|
|
if backoff > 30*time.Second {
|
|
backoff = 30 * time.Second
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
backoff = 5 * time.Second
|
|
for _, update := range updates {
|
|
if update.UpdateID >= offset {
|
|
offset = update.UpdateID + 1
|
|
}
|
|
if update.CallbackQuery != nil {
|
|
if update.CallbackQuery.Message != nil && strconv.FormatInt(update.CallbackQuery.Message.Chat.ID, 10) != chatID {
|
|
continue
|
|
}
|
|
if err := b.handleCallbackQuery(ctx, token, chatID, update.CallbackQuery); err != nil {
|
|
log.Printf("telegram bot callback failed: %v", err)
|
|
}
|
|
continue
|
|
}
|
|
if update.Message == nil {
|
|
continue
|
|
}
|
|
if strconv.FormatInt(update.Message.Chat.ID, 10) != chatID {
|
|
continue
|
|
}
|
|
if err := b.handleMessage(ctx, token, chatID, update.Message); err != nil {
|
|
log.Printf("telegram bot command failed: %v", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (b *telegramBot) commandCredentials() (bool, string, string) {
|
|
if b == nil || b.settings == nil {
|
|
return false, "", ""
|
|
}
|
|
global := b.settings.snapshot()
|
|
token := strings.TrimSpace(global.TelegramBotToken)
|
|
chatID := strings.TrimSpace(global.TelegramChatID)
|
|
if token == "" || chatID == "" {
|
|
return false, token, chatID
|
|
}
|
|
return global.TelegramCommandsEnabled, token, chatID
|
|
}
|
|
|
|
func (b *telegramBot) syncCommandMenu(ctx context.Context, token string, enabled bool, force bool) error {
|
|
if b == nil || b.server == nil || b.server.notifier == nil || b.server.notifier.client == nil {
|
|
return nil
|
|
}
|
|
token = strings.TrimSpace(token)
|
|
if token == "" {
|
|
return nil
|
|
}
|
|
state := "disabled"
|
|
if enabled {
|
|
state = "enabled:" + token
|
|
}
|
|
b.menuMu.Lock()
|
|
if !force && b.menuState == state {
|
|
b.menuMu.Unlock()
|
|
return nil
|
|
}
|
|
b.menuMu.Unlock()
|
|
var err error
|
|
if enabled {
|
|
err = b.server.notifier.setTelegramCommandMenu(ctx, token, telegramCommandMenu())
|
|
} else {
|
|
err = b.server.notifier.deleteTelegramCommandMenu(ctx, token)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
b.menuMu.Lock()
|
|
b.menuState = state
|
|
b.menuMu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
type telegramBotCommand struct {
|
|
Command string `json:"command"`
|
|
Description string `json:"description"`
|
|
}
|
|
|
|
func telegramCommandMenu() []telegramBotCommand {
|
|
return []telegramBotCommand{
|
|
{Command: "start", Description: "Show available commands"},
|
|
{Command: "help", Description: "Show available commands"},
|
|
{Command: "printers", Description: "List printers"},
|
|
{Command: "status", Description: "Show printer status, temperatures, and fans"},
|
|
{Command: "set", Description: "Set heater temperature"},
|
|
{Command: "camera", Description: "Pick a camera and send a snapshot"},
|
|
{Command: "print", Description: "Choose a recent file to print"},
|
|
{Command: "jobs", Description: "List recent jobs"},
|
|
{Command: "reprint", Description: "Restart the last print job"},
|
|
}
|
|
}
|
|
|
|
func (b *telegramBot) fetchUpdates(ctx context.Context, token string, offset int64) ([]telegramUpdate, error) {
|
|
endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/getUpdates", token)
|
|
form := url.Values{}
|
|
form.Set("timeout", "25")
|
|
form.Set("offset", strconv.FormatInt(offset, 10))
|
|
form.Set("allowed_updates", `["message","callback_query"]`)
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
resp, err := b.client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
detail := strings.TrimSpace(string(body))
|
|
if detail != "" {
|
|
return nil, fmt.Errorf("telegram getUpdates failed: %s: %s", resp.Status, detail)
|
|
}
|
|
return nil, fmt.Errorf("telegram getUpdates failed: %s", resp.Status)
|
|
}
|
|
var parsed struct {
|
|
OK bool `json:"ok"`
|
|
Result []telegramUpdate `json:"result"`
|
|
}
|
|
if err := json.Unmarshal(body, &parsed); err != nil {
|
|
return nil, err
|
|
}
|
|
return parsed.Result, nil
|
|
}
|
|
|
|
func (b *telegramBot) handleMessage(ctx context.Context, token, chatID string, msg *telegramMessage) error {
|
|
command, args := parseTelegramCommand(msg.Text)
|
|
if command == "" {
|
|
return nil
|
|
}
|
|
switch command {
|
|
case "start", "help":
|
|
return b.sendText(ctx, token, chatID, telegramHelpMessage())
|
|
case "printers":
|
|
return b.sendText(ctx, token, chatID, b.buildPrintersMessage())
|
|
case "status":
|
|
if strings.TrimSpace(args) == "" {
|
|
return b.sendPrinterSelection(ctx, token, chatID, "status")
|
|
}
|
|
printer, err := b.resolvePrinter(args)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, err.Error())
|
|
}
|
|
return b.sendPrinterStatus(ctx, token, chatID, printer)
|
|
case "camera":
|
|
if strings.TrimSpace(args) == "" {
|
|
return b.sendPrinterSelection(ctx, token, chatID, "camera")
|
|
}
|
|
printer, err := b.resolvePrinter(args)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, err.Error())
|
|
}
|
|
return b.sendCameraSelection(ctx, token, chatID, printer)
|
|
case "set":
|
|
printerQuery, heater, target, err := parseTelegramTemperatureSetArgs(args)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, err.Error())
|
|
}
|
|
if printerQuery == "" {
|
|
if printer, resolveErr := b.resolvePrinter(""); resolveErr == nil {
|
|
return b.sendTemperatureSetConfirmation(ctx, token, chatID, printer, telegramTemperatureSelection{
|
|
PrinterID: printer.record.PrinterID,
|
|
Heater: heater,
|
|
Target: target,
|
|
CreatedAt: time.Now().UTC(),
|
|
})
|
|
}
|
|
return b.sendTemperaturePrinterSelection(ctx, token, chatID, heater, target)
|
|
}
|
|
printer, err := b.resolvePrinter(printerQuery)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, err.Error())
|
|
}
|
|
return b.sendTemperatureSetConfirmation(ctx, token, chatID, printer, telegramTemperatureSelection{
|
|
PrinterID: printer.record.PrinterID,
|
|
Heater: heater,
|
|
Target: target,
|
|
CreatedAt: time.Now().UTC(),
|
|
})
|
|
case "print":
|
|
if strings.TrimSpace(args) == "" {
|
|
return b.sendPrinterSelection(ctx, token, chatID, "print")
|
|
}
|
|
printer, err := b.resolvePrinter(args)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, err.Error())
|
|
}
|
|
return b.sendPrintSelection(ctx, token, chatID, printer)
|
|
case "reprint", "restartlast", "restartjob":
|
|
if strings.TrimSpace(args) == "" {
|
|
return b.sendPrinterSelection(ctx, token, chatID, "reprint")
|
|
}
|
|
printer, err := b.resolvePrinter(args)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, err.Error())
|
|
}
|
|
return b.sendReprintConfirmation(ctx, token, chatID, printer)
|
|
case "jobs":
|
|
if strings.TrimSpace(args) == "" {
|
|
return b.sendPrinterSelection(ctx, token, chatID, "jobs")
|
|
}
|
|
printer, err := b.resolvePrinter(args)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, err.Error())
|
|
}
|
|
return b.sendJobHistory(ctx, token, chatID, printer)
|
|
default:
|
|
return b.sendText(ctx, token, chatID, telegramHelpMessage())
|
|
}
|
|
}
|
|
|
|
func (b *telegramBot) sendText(ctx context.Context, token, chatID, text string) error {
|
|
if strings.TrimSpace(text) == "" {
|
|
return nil
|
|
}
|
|
return b.server.notifier.sendTelegramMessage(ctx, token, chatID, text)
|
|
}
|
|
|
|
func (b *telegramBot) sendPrinterSelection(ctx context.Context, token, chatID, command string) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
records := b.printerSelectionRecords()
|
|
if len(records) == 0 {
|
|
return b.sendText(ctx, token, chatID, "No printers are known yet.")
|
|
}
|
|
rows := make([][]map[string]string, 0, len(records))
|
|
lines := []string{
|
|
fmt.Sprintf("Select a printer for /%s:", command),
|
|
}
|
|
for _, record := range records {
|
|
name := strings.TrimSpace(record.DisplayName)
|
|
if name == "" {
|
|
name = record.PrinterID
|
|
}
|
|
rows = append(rows, []map[string]string{
|
|
{
|
|
"text": truncateTelegramButtonLabel(name),
|
|
"callback_data": command + ":" + url.QueryEscape(record.PrinterID),
|
|
},
|
|
})
|
|
lines = append(lines, fmt.Sprintf("- %s (%s)", name, record.PrinterID))
|
|
}
|
|
markup := map[string]any{
|
|
"inline_keyboard": rows,
|
|
}
|
|
return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, strings.Join(lines, "\n"), markup)
|
|
}
|
|
|
|
func (b *telegramBot) sendPrinterSnapshot(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error {
|
|
if printer.health == nil {
|
|
return b.sendText(ctx, token, chatID, b.buildPrinterStatusMessage(printer))
|
|
}
|
|
snapshot, snapshotName, err := b.server.capturePrinterNotificationSnapshot(printer.record.PrinterID, printer.health)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nSnapshot unavailable: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
caption := b.buildPrinterStatusMessage(printer)
|
|
if err := b.server.notifier.sendTelegramPhoto(ctx, token, chatID, caption, snapshot, snapshotName); err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nSnapshot send failed: %v", caption, err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (b *telegramBot) sendCameraSelection(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
cameras := snapshotCapableCameras(printer.health)
|
|
if len(cameras) == 0 {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nNo snapshot-capable cameras were found.", b.buildPrinterStatusMessage(printer)))
|
|
}
|
|
if len(cameras) == 1 {
|
|
return b.sendCameraSnapshot(ctx, token, chatID, printer, cameras[0].Name)
|
|
}
|
|
rows := make([][]map[string]string, 0, len(cameras))
|
|
lines := []string{
|
|
b.buildPrinterStatusMessage(printer),
|
|
"Select a camera to send a snapshot:",
|
|
}
|
|
for _, camera := range cameras {
|
|
name := strings.TrimSpace(camera.Name)
|
|
tokenID, err := b.storeCameraSelection(telegramCameraSelection{
|
|
PrinterID: printer.record.PrinterID,
|
|
CameraName: name,
|
|
CreatedAt: time.Now().UTC(),
|
|
})
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nFailed to prepare camera selection: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
rows = append(rows, []map[string]string{
|
|
{
|
|
"text": truncateTelegramButtonLabel(name),
|
|
"callback_data": "camera-shot:" + tokenID,
|
|
},
|
|
})
|
|
lines = append(lines, fmt.Sprintf("- %s", name))
|
|
}
|
|
return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, strings.Join(lines, "\n"), map[string]any{"inline_keyboard": rows})
|
|
}
|
|
|
|
func (b *telegramBot) sendCameraSnapshot(ctx context.Context, token, chatID string, printer telegramPrinterTarget, cameraName string) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
cameraName = strings.TrimSpace(cameraName)
|
|
if cameraName == "" {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nSnapshot unavailable: no camera selected.", b.buildPrinterStatusMessage(printer)))
|
|
}
|
|
if printer.health == nil {
|
|
return b.sendText(ctx, token, chatID, b.buildPrinterStatusMessage(printer))
|
|
}
|
|
snapshot, snapshotName, err := b.server.capturePrinterNotificationSnapshotWithCamera(printer.record.PrinterID, printer.health, cameraName)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nSnapshot unavailable: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
caption := b.buildPrinterStatusMessage(printer)
|
|
if err := b.server.notifier.sendTelegramPhoto(ctx, token, chatID, caption, snapshot, snapshotName); err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nSnapshot send failed: %v", caption, err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (b *telegramBot) sendPrinterStatus(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
message := b.buildPrinterStatusMessage(printer)
|
|
if liveStatus := printerLiveStatus(printer.health); len(liveStatus) > 0 {
|
|
detailed := b.buildPrinterStatusMessageWithLiveData(printer, liveStatus)
|
|
return b.sendText(ctx, token, chatID, detailed)
|
|
}
|
|
t := b.server.tunnelForPrinter(printer.record.PrinterID)
|
|
if t == nil {
|
|
return b.sendText(ctx, token, chatID, message)
|
|
}
|
|
objects := liveObjectQueryNames()
|
|
log.Printf("telegram status live query printer_id=%s objects=%v", printer.record.PrinterID, objects)
|
|
status, err := b.server.fetchPrinterObjectStatus(ctx, t, objects)
|
|
if err != nil {
|
|
log.Printf("telegram status live query failed printer_id=%s error=%v", printer.record.PrinterID, err)
|
|
return b.sendText(ctx, token, chatID, message)
|
|
}
|
|
detailed := b.buildPrinterStatusMessageWithLiveData(printer, status)
|
|
return b.sendText(ctx, token, chatID, detailed)
|
|
}
|
|
|
|
func printerLiveStatus(health *protocol.Health) map[string]any {
|
|
if health == nil || health.PrintStatus == nil {
|
|
return nil
|
|
}
|
|
status := health.PrintStatus.MoonrakerStatus
|
|
if len(status) == 0 {
|
|
return nil
|
|
}
|
|
return status
|
|
}
|
|
|
|
func (b *telegramBot) sendTemperaturePrinterSelection(ctx context.Context, token, chatID, heater string, target float64) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
records := b.printerSelectionRecords()
|
|
if len(records) == 0 {
|
|
return b.sendText(ctx, token, chatID, "No printers are known yet.")
|
|
}
|
|
selectionID, err := b.storeTemperatureSelection(telegramTemperatureSelection{
|
|
Heater: heater,
|
|
Target: target,
|
|
CreatedAt: time.Now().UTC(),
|
|
})
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("Failed to prepare temperature selection: %v", err))
|
|
}
|
|
rows := make([][]map[string]string, 0, len(records))
|
|
lines := []string{fmt.Sprintf("Select a printer for /set %s %.1f:", temperatureHeaterDisplayName(heater), target)}
|
|
for _, record := range records {
|
|
name := strings.TrimSpace(record.DisplayName)
|
|
if name == "" {
|
|
name = record.PrinterID
|
|
}
|
|
rows = append(rows, []map[string]string{
|
|
{
|
|
"text": truncateTelegramButtonLabel(name),
|
|
"callback_data": "set-temp:" + selectionID + ":" + url.QueryEscape(record.PrinterID),
|
|
},
|
|
})
|
|
lines = append(lines, fmt.Sprintf("- %s (%s)", name, record.PrinterID))
|
|
}
|
|
return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, strings.Join(lines, "\n"), map[string]any{"inline_keyboard": rows})
|
|
}
|
|
|
|
func (b *telegramBot) sendTemperatureSetConfirmation(ctx context.Context, token, chatID string, printer telegramPrinterTarget, selection telegramTemperatureSelection) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
message := b.buildPrinterStatusMessage(printer)
|
|
if mode := strings.ToLower(strings.TrimSpace(printer.record.ControlMode)); mode == "readonly" {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nTemperature set unavailable: printer control mode is read-only.", message))
|
|
}
|
|
t := b.server.tunnelForPrinter(printer.record.PrinterID)
|
|
if t == nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nTemperature set unavailable: printer is not connected.", message))
|
|
}
|
|
heaterName, err := normalizeTemperatureHeater(selection.Heater)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nTemperature set unavailable: %v", message, err))
|
|
}
|
|
if selection.Target < 0 {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nTemperature set unavailable: target temperature must be non-negative.", message))
|
|
}
|
|
selection.Heater = heaterName
|
|
selection.PrinterID = printer.record.PrinterID
|
|
tokenID, err := b.storeTemperatureSelection(selection)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nTemperature confirmation unavailable: %v", message, err))
|
|
}
|
|
if printer.health == nil {
|
|
printer.health = &protocol.Health{}
|
|
}
|
|
snapshot, snapshotName, err := b.server.capturePrinterNotificationSnapshot(printer.record.PrinterID, printer.health)
|
|
caption := b.buildTemperatureConfirmationMessage(printer, selection)
|
|
markup := map[string]any{
|
|
"inline_keyboard": [][]map[string]string{
|
|
{
|
|
{
|
|
"text": "Set temperature",
|
|
"callback_data": "temp-confirm:" + tokenID,
|
|
},
|
|
{
|
|
"text": "Cancel",
|
|
"callback_data": "temp-cancel:" + tokenID,
|
|
},
|
|
},
|
|
},
|
|
}
|
|
if err == nil && len(snapshot) > 0 {
|
|
return b.server.notifier.sendTelegramPhotoWithMarkup(ctx, token, chatID, caption, snapshot, snapshotName, markup)
|
|
}
|
|
return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, caption, markup)
|
|
}
|
|
|
|
func (b *telegramBot) startSelectedTemperatureSet(ctx context.Context, token, chatID, callbackID string, printer telegramPrinterTarget, selection telegramTemperatureSelection) error {
|
|
if selection.PrinterID == "" {
|
|
return b.answerCallbackQuery(ctx, token, callbackID, "This temperature selection is no longer available.")
|
|
}
|
|
t := b.server.tunnelForPrinter(selection.PrinterID)
|
|
if t == nil {
|
|
return b.answerCallbackQuery(ctx, token, callbackID, "The printer is no longer connected.")
|
|
}
|
|
if mode := strings.ToLower(strings.TrimSpace(printer.record.ControlMode)); mode == "readonly" {
|
|
return b.answerCallbackQuery(ctx, token, callbackID, "Printer control mode is read-only.")
|
|
}
|
|
if err := b.server.setPrinterHeaterTarget(ctx, t, selection.Heater, selection.Target); err != nil {
|
|
return b.answerCallbackQuery(ctx, token, callbackID, fmt.Sprintf("Failed to set %s to %.1f°C: %v", temperatureHeaterDisplayName(selection.Heater), selection.Target, err))
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, callbackID, "Setting heater target..."); err != nil {
|
|
return err
|
|
}
|
|
name := strings.TrimSpace(printer.record.DisplayName)
|
|
if name == "" {
|
|
name = printer.record.PrinterID
|
|
}
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("Printer: %s\nEvent: Set %s target\nTarget: %.1f°C", name, temperatureHeaterDisplayName(selection.Heater), selection.Target))
|
|
}
|
|
|
|
func (b *telegramBot) sendReprintConfirmation(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
if printer.health == nil || printer.health.PrintStatus == nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: printer is not connected.", b.buildPrinterStatusMessage(printer)))
|
|
}
|
|
currentState := strings.ToLower(strings.TrimSpace(printer.health.PrintStatus.State))
|
|
switch currentState {
|
|
case "printing", "paused":
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: printer is currently %s.", b.buildPrinterStatusMessage(printer), currentState))
|
|
}
|
|
if mode := strings.ToLower(strings.TrimSpace(printer.record.ControlMode)); mode == "readonly" {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: printer control mode is read-only.", b.buildPrinterStatusMessage(printer)))
|
|
}
|
|
t := b.server.tunnelForPrinter(printer.record.PrinterID)
|
|
if t == nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: printer is not connected.", b.buildPrinterStatusMessage(printer)))
|
|
}
|
|
filename, historyStatus, err := b.server.lastPrintableJobFilename(ctx, t)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
if filename == "" {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: no recent printable job was found.", b.buildPrinterStatusMessage(printer)))
|
|
}
|
|
selection := telegramPrintSelection{
|
|
PrinterID: printer.record.PrinterID,
|
|
Filename: filename,
|
|
Label: filename,
|
|
CreatedAt: time.Now().UTC(),
|
|
}
|
|
tokenID, err := b.storeSelection(selection)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint unavailable: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
selectionToken := tokenID
|
|
selection.Label = formatJobSelectionLabel(filename, historyStatus)
|
|
return b.sendReprintConfirmationWithToken(ctx, token, chatID, printer, selection, selectionToken)
|
|
}
|
|
|
|
func (b *telegramBot) handleCallbackQuery(ctx context.Context, token, chatID string, query *telegramCallbackQuery) error {
|
|
if query == nil {
|
|
return nil
|
|
}
|
|
action := parseTelegramCallbackAction(strings.TrimSpace(query.Data))
|
|
switch action.Kind {
|
|
case "status":
|
|
record, ok := b.printerRecordFromCallback(action.ID)
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.")
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, query.ID, "Loading printer status."); err != nil {
|
|
return err
|
|
}
|
|
return b.sendPrinterStatus(ctx, token, chatID, b.resolvePrinterByRecord(record))
|
|
case "print":
|
|
record, ok := b.printerRecordFromCallback(action.ID)
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.")
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, query.ID, "Loading recent jobs."); err != nil {
|
|
return err
|
|
}
|
|
return b.sendPrintSelection(ctx, token, chatID, b.resolvePrinterByRecord(record))
|
|
case "reprint":
|
|
record, ok := b.printerRecordFromCallback(action.ID)
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.")
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, query.ID, "Preparing confirmation."); err != nil {
|
|
return err
|
|
}
|
|
return b.sendReprintConfirmation(ctx, token, chatID, b.resolvePrinterByRecord(record))
|
|
case "jobs":
|
|
record, ok := b.printerRecordFromCallback(action.ID)
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.")
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, query.ID, "Loading recent jobs."); err != nil {
|
|
return err
|
|
}
|
|
return b.sendJobHistory(ctx, token, chatID, b.resolvePrinterByRecord(record))
|
|
case "camera":
|
|
record, ok := b.printerRecordFromCallback(action.ID)
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.")
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, query.ID, "Loading cameras."); err != nil {
|
|
return err
|
|
}
|
|
return b.sendCameraSelection(ctx, token, chatID, b.resolvePrinterByRecord(record))
|
|
case "set-temp":
|
|
parts := strings.SplitN(action.ID, ":", 2)
|
|
if len(parts) != 2 {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This temperature selection expired.")
|
|
}
|
|
selection, ok := b.consumeTemperatureSelection(parts[0])
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This temperature selection expired.")
|
|
}
|
|
printerID, err := url.QueryUnescape(parts[1])
|
|
if err != nil {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This temperature selection expired.")
|
|
}
|
|
record, ok := b.printerRecordFromCallback(printerID)
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This printer selection expired.")
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, query.ID, "Preparing heater confirmation."); err != nil {
|
|
return err
|
|
}
|
|
selection.PrinterID = record.PrinterID
|
|
return b.sendTemperatureSetConfirmation(ctx, token, chatID, b.resolvePrinterByRecord(record), selection)
|
|
case "temp-confirm":
|
|
selection, ok := b.consumeTemperatureSelection(action.ID)
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This temperature selection expired.")
|
|
}
|
|
record, ok := b.server.printerSettings.snapshot(selection.PrinterID)
|
|
if !ok || record.PrinterID == "" {
|
|
record = printerSettingsRecord{PrinterID: selection.PrinterID}
|
|
}
|
|
printer := b.resolvePrinterByRecord(record)
|
|
if err := b.startSelectedTemperatureSet(ctx, token, chatID, query.ID, printer, selection); err != nil {
|
|
return err
|
|
}
|
|
if query.Message != nil {
|
|
_ = b.server.notifier.deleteTelegramMessage(ctx, token, chatID, query.Message.MessageID)
|
|
}
|
|
return nil
|
|
case "temp-cancel":
|
|
if _, ok := b.consumeTemperatureSelection(action.ID); !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This temperature selection expired.")
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, query.ID, "Cancelled."); err != nil {
|
|
return err
|
|
}
|
|
if query.Message != nil {
|
|
_ = b.server.notifier.deleteTelegramMessage(ctx, token, chatID, query.Message.MessageID)
|
|
}
|
|
return nil
|
|
case "camera-shot":
|
|
selection, ok := b.consumeCameraSelection(action.ID)
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This camera selection expired.")
|
|
}
|
|
record, ok := b.server.printerSettings.snapshot(selection.PrinterID)
|
|
if !ok || record.PrinterID == "" {
|
|
record = printerSettingsRecord{PrinterID: selection.PrinterID}
|
|
}
|
|
printer := b.resolvePrinterByRecord(record)
|
|
if err := b.answerCallbackQuery(ctx, token, query.ID, "Sending snapshot."); err != nil {
|
|
return err
|
|
}
|
|
return b.sendCameraSnapshot(ctx, token, chatID, printer, selection.CameraName)
|
|
case "select":
|
|
selection, ok := b.peekSelection(action.ID)
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This print selection expired.")
|
|
}
|
|
record, _ := b.server.printerSettings.snapshot(selection.PrinterID)
|
|
if record.PrinterID == "" {
|
|
record = printerSettingsRecord{PrinterID: selection.PrinterID}
|
|
}
|
|
printer := b.resolvePrinterByRecord(record)
|
|
if err := b.sendPrintConfirmation(ctx, token, chatID, printer, selection); err != nil {
|
|
return err
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, query.ID, "Review the snapshot below."); err != nil {
|
|
return err
|
|
}
|
|
_, _ = b.consumeSelection(action.ID)
|
|
return nil
|
|
case "confirm":
|
|
selection, ok := b.consumeSelection(action.ID)
|
|
if !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This print selection expired.")
|
|
}
|
|
record, _ := b.server.printerSettings.snapshot(selection.PrinterID)
|
|
if record.PrinterID == "" {
|
|
record = printerSettingsRecord{PrinterID: selection.PrinterID}
|
|
}
|
|
printer := b.resolvePrinterByRecord(record)
|
|
if err := b.startSelectedPrint(ctx, token, chatID, query.ID, printer, selection); err != nil {
|
|
return err
|
|
}
|
|
if query.Message != nil {
|
|
_ = b.server.notifier.deleteTelegramMessage(ctx, token, chatID, query.Message.MessageID)
|
|
}
|
|
return nil
|
|
case "cancel":
|
|
if _, ok := b.consumeSelection(action.ID); !ok {
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This print selection expired.")
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, query.ID, "Cancelled."); err != nil {
|
|
return err
|
|
}
|
|
if query.Message != nil {
|
|
_ = b.server.notifier.deleteTelegramMessage(ctx, token, chatID, query.Message.MessageID)
|
|
}
|
|
return nil
|
|
default:
|
|
return b.answerCallbackQuery(ctx, token, query.ID, "This action is no longer available.")
|
|
}
|
|
}
|
|
|
|
func (b *telegramBot) sendPrintSelection(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
t := b.server.tunnelForPrinter(printer.record.PrinterID)
|
|
if t == nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint selection unavailable: printer is not connected.", b.buildPrinterStatusMessage(printer)))
|
|
}
|
|
jobs, err := b.server.fetchPrinterJobHistory(ctx, t)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint selection unavailable: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
summaries := selectPrintableJobs(jobs, 5)
|
|
if len(summaries) == 0 {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nNo recent printable jobs were found.", b.buildPrinterStatusMessage(printer)))
|
|
}
|
|
rows := make([][]map[string]string, 0, len(summaries))
|
|
lines := []string{
|
|
b.buildPrinterStatusMessage(printer),
|
|
"Select a job to review before printing:",
|
|
}
|
|
for _, job := range summaries {
|
|
tokenID, err := b.storeSelection(telegramPrintSelection{
|
|
PrinterID: printer.record.PrinterID,
|
|
Filename: job.Filename,
|
|
Label: job.Label,
|
|
CreatedAt: time.Now().UTC(),
|
|
})
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nFailed to prepare print selection: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
rows = append(rows, []map[string]string{
|
|
{
|
|
"text": job.ButtonLabel,
|
|
"callback_data": "select:" + tokenID,
|
|
},
|
|
})
|
|
lines = append(lines, fmt.Sprintf("- %s", job.Label))
|
|
}
|
|
markup := map[string]any{
|
|
"inline_keyboard": rows,
|
|
}
|
|
return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, strings.Join(lines, "\n"), markup)
|
|
}
|
|
|
|
func (b *telegramBot) sendJobHistory(ctx context.Context, token, chatID string, printer telegramPrinterTarget) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
t := b.server.tunnelForPrinter(printer.record.PrinterID)
|
|
if t == nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nJob history unavailable: printer is not connected.", b.buildPrinterStatusMessage(printer)))
|
|
}
|
|
jobs, err := b.server.fetchPrinterJobHistory(ctx, t)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nJob history unavailable: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
if len(jobs) == 0 {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nNo recent jobs were found.", b.buildPrinterStatusMessage(printer)))
|
|
}
|
|
return b.sendText(ctx, token, chatID, strings.Join(buildJobHistoryLines(b.buildPrinterStatusMessage(printer), jobs), "\n"))
|
|
}
|
|
|
|
func buildJobHistoryLines(header string, jobs []map[string]any) []string {
|
|
lines := []string{
|
|
header,
|
|
"Recent jobs:",
|
|
}
|
|
for _, job := range jobs {
|
|
filename := strings.TrimSpace(stringFromAny(job["filename"]))
|
|
if filename == "" {
|
|
continue
|
|
}
|
|
status := strings.TrimSpace(stringFromAny(job["status"]))
|
|
if status != "" {
|
|
lines = append(lines, fmt.Sprintf("- %s (%s)", filename, status))
|
|
continue
|
|
}
|
|
lines = append(lines, fmt.Sprintf("- %s", filename))
|
|
}
|
|
if len(lines) == 2 {
|
|
lines = append(lines, "- No printable job entries were found.")
|
|
}
|
|
return lines
|
|
}
|
|
|
|
func (b *telegramBot) sendPrintConfirmation(ctx context.Context, token, chatID string, printer telegramPrinterTarget, selection telegramPrintSelection) error {
|
|
if selection.PrinterID == "" || selection.Filename == "" {
|
|
return b.sendText(ctx, token, chatID, "This print selection is no longer available.")
|
|
}
|
|
return b.sendPrintConfirmationWithToken(ctx, token, chatID, printer, selection, "", "select")
|
|
}
|
|
|
|
func (b *telegramBot) sendPrintConfirmationWithToken(ctx context.Context, token, chatID string, printer telegramPrinterTarget, selection telegramPrintSelection, selectionToken string, source string) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
if printer.health == nil {
|
|
printer.health = &protocol.Health{}
|
|
}
|
|
snapshot, snapshotName, err := b.server.capturePrinterNotificationSnapshot(printer.record.PrinterID, printer.health)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint confirmation unavailable: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
caption := b.buildPrintConfirmationMessage(printer, selection, source)
|
|
if selectionToken == "" {
|
|
tokenID, err := b.storeSelection(selection)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint confirmation unavailable: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
selectionToken = tokenID
|
|
}
|
|
markup := map[string]any{
|
|
"inline_keyboard": [][]map[string]string{
|
|
{
|
|
{
|
|
"text": "Confirm",
|
|
"callback_data": "confirm:" + selectionToken,
|
|
},
|
|
{
|
|
"text": "Cancel",
|
|
"callback_data": "cancel:" + selectionToken,
|
|
},
|
|
},
|
|
},
|
|
}
|
|
if len(snapshot) > 0 {
|
|
return b.server.notifier.sendTelegramPhotoWithMarkup(ctx, token, chatID, caption, snapshot, snapshotName, markup)
|
|
}
|
|
return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, caption, markup)
|
|
}
|
|
|
|
func (b *telegramBot) sendReprintConfirmationWithToken(ctx context.Context, token, chatID string, printer telegramPrinterTarget, selection telegramPrintSelection, selectionToken string) error {
|
|
if b == nil || b.server == nil {
|
|
return b.sendText(ctx, token, chatID, "Telegram bot is unavailable.")
|
|
}
|
|
if printer.health == nil {
|
|
printer.health = &protocol.Health{}
|
|
}
|
|
snapshot, snapshotName, err := b.server.capturePrinterNotificationSnapshot(printer.record.PrinterID, printer.health)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint confirmation unavailable: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
caption := b.buildReprintConfirmationMessage(printer, selection)
|
|
if selectionToken == "" {
|
|
tokenID, err := b.storeSelection(selection)
|
|
if err != nil {
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("%s\nPrint confirmation unavailable: %v", b.buildPrinterStatusMessage(printer), err))
|
|
}
|
|
selectionToken = tokenID
|
|
}
|
|
markup := map[string]any{
|
|
"inline_keyboard": [][]map[string]string{
|
|
{
|
|
{
|
|
"text": "Confirm",
|
|
"callback_data": "confirm:" + selectionToken,
|
|
},
|
|
{
|
|
"text": "Cancel",
|
|
"callback_data": "cancel:" + selectionToken,
|
|
},
|
|
},
|
|
},
|
|
}
|
|
if len(snapshot) > 0 {
|
|
return b.server.notifier.sendTelegramPhotoWithMarkup(ctx, token, chatID, caption, snapshot, snapshotName, markup)
|
|
}
|
|
return b.server.notifier.sendTelegramMessageWithMarkup(ctx, token, chatID, caption, markup)
|
|
}
|
|
|
|
func (b *telegramBot) startSelectedPrint(ctx context.Context, token, chatID, callbackID string, printer telegramPrinterTarget, selection telegramPrintSelection) error {
|
|
if selection.PrinterID == "" || selection.Filename == "" {
|
|
return b.answerCallbackQuery(ctx, token, callbackID, "This print selection is no longer available.")
|
|
}
|
|
t := b.server.tunnelForPrinter(selection.PrinterID)
|
|
if t == nil {
|
|
return b.answerCallbackQuery(ctx, token, callbackID, "The printer is no longer connected.")
|
|
}
|
|
if err := b.server.startPrinterJob(ctx, t, selection.Filename); err != nil {
|
|
return b.answerCallbackQuery(ctx, token, callbackID, fmt.Sprintf("Failed to start %s: %v", selection.Label, err))
|
|
}
|
|
if err := b.answerCallbackQuery(ctx, token, callbackID, "Starting print..."); err != nil {
|
|
return err
|
|
}
|
|
name := strings.TrimSpace(printer.record.DisplayName)
|
|
if name == "" {
|
|
name = printer.record.PrinterID
|
|
}
|
|
return b.sendText(ctx, token, chatID, fmt.Sprintf("Printer: %s\nEvent: Started print job\nFile: %s", name, selection.Filename))
|
|
}
|
|
|
|
func (b *telegramBot) answerCallbackQuery(ctx context.Context, token, callbackID, text string) error {
|
|
endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/answerCallbackQuery", token)
|
|
form := url.Values{}
|
|
form.Set("callback_query_id", callbackID)
|
|
if text = strings.TrimSpace(text); text != "" {
|
|
form.Set("text", text)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
resp, err := b.server.notifier.client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
|
detail := strings.TrimSpace(string(body))
|
|
if detail != "" {
|
|
return fmt.Errorf("telegram answerCallbackQuery failed: %s: %s", resp.Status, detail)
|
|
}
|
|
return fmt.Errorf("telegram answerCallbackQuery failed: %s", resp.Status)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (b *telegramBot) storeSelection(selection telegramPrintSelection) (string, error) {
|
|
id, err := newID()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
if b.selections == nil {
|
|
b.selections = make(map[string]telegramPrintSelection)
|
|
}
|
|
b.pruneSelectionsLocked()
|
|
b.selections[id] = selection
|
|
return id, nil
|
|
}
|
|
|
|
func (b *telegramBot) storeCameraSelection(selection telegramCameraSelection) (string, error) {
|
|
id, err := newID()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
if b.cameraSelections == nil {
|
|
b.cameraSelections = make(map[string]telegramCameraSelection)
|
|
}
|
|
b.pruneCameraSelectionsLocked()
|
|
b.cameraSelections[id] = selection
|
|
return id, nil
|
|
}
|
|
|
|
func (b *telegramBot) storeTemperatureSelection(selection telegramTemperatureSelection) (string, error) {
|
|
id, err := newID()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
if b.temperatureSelections == nil {
|
|
b.temperatureSelections = make(map[string]telegramTemperatureSelection)
|
|
}
|
|
b.pruneTemperatureSelectionsLocked()
|
|
b.temperatureSelections[id] = selection
|
|
return id, nil
|
|
}
|
|
|
|
func (b *telegramBot) peekSelection(id string) (telegramPrintSelection, bool) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
if b.selections == nil {
|
|
return telegramPrintSelection{}, false
|
|
}
|
|
b.pruneSelectionsLocked()
|
|
selection, ok := b.selections[id]
|
|
return selection, ok
|
|
}
|
|
|
|
func (b *telegramBot) consumeSelection(id string) (telegramPrintSelection, bool) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
if b.selections == nil {
|
|
return telegramPrintSelection{}, false
|
|
}
|
|
b.pruneSelectionsLocked()
|
|
selection, ok := b.selections[id]
|
|
if ok {
|
|
delete(b.selections, id)
|
|
}
|
|
return selection, ok
|
|
}
|
|
|
|
func (b *telegramBot) consumeCameraSelection(id string) (telegramCameraSelection, bool) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
if b.cameraSelections == nil {
|
|
return telegramCameraSelection{}, false
|
|
}
|
|
b.pruneCameraSelectionsLocked()
|
|
selection, ok := b.cameraSelections[id]
|
|
if ok {
|
|
delete(b.cameraSelections, id)
|
|
}
|
|
return selection, ok
|
|
}
|
|
|
|
func (b *telegramBot) consumeTemperatureSelection(id string) (telegramTemperatureSelection, bool) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
if b.temperatureSelections == nil {
|
|
return telegramTemperatureSelection{}, false
|
|
}
|
|
b.pruneTemperatureSelectionsLocked()
|
|
selection, ok := b.temperatureSelections[id]
|
|
if !ok {
|
|
return telegramTemperatureSelection{}, false
|
|
}
|
|
delete(b.temperatureSelections, id)
|
|
return selection, true
|
|
}
|
|
|
|
func (b *telegramBot) pruneSelectionsLocked() {
|
|
if len(b.selections) == 0 {
|
|
return
|
|
}
|
|
now := time.Now().UTC()
|
|
for id, selection := range b.selections {
|
|
if now.Sub(selection.CreatedAt) > 15*time.Minute {
|
|
delete(b.selections, id)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (b *telegramBot) pruneCameraSelectionsLocked() {
|
|
if len(b.cameraSelections) == 0 {
|
|
return
|
|
}
|
|
now := time.Now().UTC()
|
|
for id, selection := range b.cameraSelections {
|
|
if now.Sub(selection.CreatedAt) > 15*time.Minute {
|
|
delete(b.cameraSelections, id)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (b *telegramBot) pruneTemperatureSelectionsLocked() {
|
|
if len(b.temperatureSelections) == 0 {
|
|
return
|
|
}
|
|
now := time.Now().UTC()
|
|
for id, selection := range b.temperatureSelections {
|
|
if now.Sub(selection.CreatedAt) > 15*time.Minute {
|
|
delete(b.temperatureSelections, id)
|
|
}
|
|
}
|
|
}
|
|
|
|
func selectPrintableJobs(jobs []map[string]any, limit int) []telegramPrintableJob {
|
|
if limit <= 0 {
|
|
limit = 5
|
|
}
|
|
out := make([]telegramPrintableJob, 0, limit)
|
|
for _, job := range jobs {
|
|
filename := strings.TrimSpace(stringFromAny(job["filename"]))
|
|
if filename == "" {
|
|
continue
|
|
}
|
|
status := strings.ToLower(strings.TrimSpace(stringFromAny(job["status"])))
|
|
if status != "" && !isTerminalJobHistoryStatus(status) {
|
|
continue
|
|
}
|
|
label := filename
|
|
if status != "" {
|
|
label = fmt.Sprintf("%s (%s)", filename, status)
|
|
}
|
|
out = append(out, telegramPrintableJob{
|
|
Filename: filename,
|
|
Label: label,
|
|
ButtonLabel: truncateTelegramButtonLabel(filename),
|
|
})
|
|
if len(out) >= limit {
|
|
break
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
type telegramPrintableFile struct {
|
|
Path string
|
|
Label string
|
|
ButtonLabel string
|
|
}
|
|
|
|
type telegramLiveObjectSummary struct {
|
|
Label string
|
|
Line string
|
|
}
|
|
|
|
func selectPrintableFiles(files []moonrakerFileInfo, limit int) []telegramPrintableFile {
|
|
if limit <= 0 {
|
|
limit = 5
|
|
}
|
|
sorted := make([]moonrakerFileInfo, 0, len(files))
|
|
for _, file := range files {
|
|
path := strings.TrimSpace(file.Path)
|
|
if path == "" {
|
|
continue
|
|
}
|
|
sorted = append(sorted, file)
|
|
}
|
|
sort.SliceStable(sorted, func(i, j int) bool {
|
|
if sorted[i].Modified == sorted[j].Modified {
|
|
return strings.ToLower(strings.TrimSpace(sorted[i].Path)) < strings.ToLower(strings.TrimSpace(sorted[j].Path))
|
|
}
|
|
return sorted[i].Modified > sorted[j].Modified
|
|
})
|
|
out := make([]telegramPrintableFile, 0, limit)
|
|
for _, file := range sorted {
|
|
filePath := strings.TrimSpace(file.Path)
|
|
if filePath == "" {
|
|
continue
|
|
}
|
|
label := filePath
|
|
out = append(out, telegramPrintableFile{
|
|
Path: filePath,
|
|
Label: label,
|
|
ButtonLabel: truncateTelegramButtonLabel(path.Base(filePath)),
|
|
})
|
|
if len(out) >= limit {
|
|
break
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func liveObjectQueryNames() []string {
|
|
return []string{
|
|
"extruder",
|
|
"extruder1",
|
|
"extruder2",
|
|
"heater_bed",
|
|
"heater_generic",
|
|
"temperature_sensor chamber",
|
|
"temperature_sensor",
|
|
"temperature_fan",
|
|
"temperature_fan chamber",
|
|
"fan",
|
|
"fan_generic",
|
|
"controller_fan",
|
|
}
|
|
}
|
|
|
|
func temperatureObjectSummary(status map[string]any) []string {
|
|
summaries := summarizeLiveObjects(status, func(name string, obj map[string]any) (string, bool) {
|
|
temp, ok := numberFromAny(obj["temperature"])
|
|
if !ok {
|
|
return "", false
|
|
}
|
|
line := fmt.Sprintf("%s: %.1f°C", name, temp)
|
|
if target, ok := numberFromAny(obj["target"]); ok && target > 0 {
|
|
line += fmt.Sprintf(" / %.1f°C", target)
|
|
}
|
|
return line, true
|
|
})
|
|
return summaries
|
|
}
|
|
|
|
func fanObjectSummary(status map[string]any) []string {
|
|
return summarizeLiveObjects(status, func(name string, obj map[string]any) (string, bool) {
|
|
speed, ok := numberFromAny(obj["speed"])
|
|
if !ok {
|
|
return "", false
|
|
}
|
|
line := fmt.Sprintf("%s: %.0f%%", name, speed*100)
|
|
if rpm, ok := numberFromAny(obj["rpm"]); ok && rpm > 0 {
|
|
line += fmt.Sprintf(" (%d rpm)", int64(rpm))
|
|
}
|
|
return line, true
|
|
})
|
|
}
|
|
|
|
func summarizeLiveObjects(status map[string]any, formatter func(string, map[string]any) (string, bool)) []string {
|
|
if len(status) == 0 {
|
|
return nil
|
|
}
|
|
type item struct {
|
|
name string
|
|
line string
|
|
}
|
|
items := make([]item, 0, len(status))
|
|
for name, value := range status {
|
|
obj, ok := value.(map[string]any)
|
|
if !ok {
|
|
continue
|
|
}
|
|
if strings.EqualFold(name, "print_stats") || strings.EqualFold(name, "display_status") || strings.EqualFold(name, "gcode_move") || strings.EqualFold(name, "toolhead") {
|
|
continue
|
|
}
|
|
line, ok := formatter(name, obj)
|
|
if !ok || strings.TrimSpace(line) == "" {
|
|
continue
|
|
}
|
|
items = append(items, item{name: strings.ToLower(strings.TrimSpace(name)), line: line})
|
|
}
|
|
sort.SliceStable(items, func(i, j int) bool {
|
|
return items[i].name < items[j].name
|
|
})
|
|
lines := make([]string, 0, len(items))
|
|
for _, item := range items {
|
|
lines = append(lines, "- "+item.line)
|
|
}
|
|
return lines
|
|
}
|
|
|
|
func numberFromAny(value any) (float64, bool) {
|
|
switch v := value.(type) {
|
|
case float64:
|
|
return v, true
|
|
case float32:
|
|
return float64(v), true
|
|
case int:
|
|
return float64(v), true
|
|
case int64:
|
|
return float64(v), true
|
|
case json.Number:
|
|
f, err := v.Float64()
|
|
return f, err == nil
|
|
default:
|
|
return 0, false
|
|
}
|
|
}
|
|
|
|
func snapshotCapableCameras(health *protocol.Health) []protocol.CameraHealth {
|
|
if health == nil {
|
|
return nil
|
|
}
|
|
cameras := make([]protocol.CameraHealth, 0, len(health.Cameras))
|
|
for _, camera := range health.Cameras {
|
|
if strings.TrimSpace(camera.Name) == "" || !camera.HasSnapshot {
|
|
continue
|
|
}
|
|
cameras = append(cameras, camera)
|
|
}
|
|
sort.SliceStable(cameras, func(i, j int) bool {
|
|
return strings.ToLower(strings.TrimSpace(cameras[i].Name)) < strings.ToLower(strings.TrimSpace(cameras[j].Name))
|
|
})
|
|
return cameras
|
|
}
|
|
|
|
func splitCameraCallbackID(value string) (string, string, bool) {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" {
|
|
return "", "", false
|
|
}
|
|
decoded, err := url.QueryUnescape(value)
|
|
if err != nil {
|
|
decoded = value
|
|
}
|
|
printerID, cameraName, ok := strings.Cut(decoded, "|")
|
|
if !ok {
|
|
return "", "", false
|
|
}
|
|
printerID = strings.TrimSpace(printerID)
|
|
cameraName = strings.TrimSpace(cameraName)
|
|
if printerID == "" || cameraName == "" {
|
|
return "", "", false
|
|
}
|
|
return printerID, cameraName, true
|
|
}
|
|
|
|
func truncateTelegramButtonLabel(value string) string {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" {
|
|
return "print"
|
|
}
|
|
runes := []rune(value)
|
|
if len(runes) <= 24 {
|
|
return value
|
|
}
|
|
return string(runes[:24]) + "..."
|
|
}
|
|
|
|
func parseTelegramCallbackAction(data string) telegramCallbackAction {
|
|
data = strings.TrimSpace(data)
|
|
if data == "" {
|
|
return telegramCallbackAction{}
|
|
}
|
|
kind, id, ok := strings.Cut(data, ":")
|
|
if !ok {
|
|
return telegramCallbackAction{}
|
|
}
|
|
decodedID, err := url.QueryUnescape(strings.TrimSpace(id))
|
|
if err != nil {
|
|
decodedID = strings.TrimSpace(id)
|
|
}
|
|
return telegramCallbackAction{Kind: strings.ToLower(strings.TrimSpace(kind)), ID: decodedID}
|
|
}
|
|
|
|
func (b *telegramBot) buildPrintConfirmationMessage(printer telegramPrinterTarget, selection telegramPrintSelection, source string) string {
|
|
name := strings.TrimSpace(printer.record.DisplayName)
|
|
if name == "" {
|
|
name = printer.record.PrinterID
|
|
}
|
|
lines := []string{
|
|
fmt.Sprintf("Printer: %s", name),
|
|
"Action: Start print",
|
|
fmt.Sprintf("File: %s", selection.Filename),
|
|
"Snapshot: review the bed before confirming",
|
|
}
|
|
if source == "print" {
|
|
lines[3] = "Snapshot: review the printer before confirming"
|
|
}
|
|
if selection.Label != "" && selection.Label != selection.Filename {
|
|
lines = append(lines, fmt.Sprintf("Selection: %s", selection.Label))
|
|
}
|
|
if printer.health != nil && printer.health.PrintStatus != nil {
|
|
if state := strings.TrimSpace(printer.health.PrintStatus.State); state != "" {
|
|
lines = append(lines, fmt.Sprintf("Current state: %s", state))
|
|
}
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
func (b *telegramBot) buildReprintConfirmationMessage(printer telegramPrinterTarget, selection telegramPrintSelection) string {
|
|
name := strings.TrimSpace(printer.record.DisplayName)
|
|
if name == "" {
|
|
name = printer.record.PrinterID
|
|
}
|
|
lines := []string{
|
|
fmt.Sprintf("Printer: %s", name),
|
|
"Action: Reprint last job",
|
|
fmt.Sprintf("File: %s", selection.Filename),
|
|
"Snapshot: review the bed before confirming",
|
|
}
|
|
if selection.Label != "" && selection.Label != selection.Filename {
|
|
lines = append(lines, fmt.Sprintf("Selection: %s", selection.Label))
|
|
}
|
|
if printer.health != nil && printer.health.PrintStatus != nil {
|
|
if state := strings.TrimSpace(printer.health.PrintStatus.State); state != "" {
|
|
lines = append(lines, fmt.Sprintf("Current state: %s", state))
|
|
}
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
func (b *telegramBot) buildTemperatureConfirmationMessage(printer telegramPrinterTarget, selection telegramTemperatureSelection) string {
|
|
name := strings.TrimSpace(printer.record.DisplayName)
|
|
if name == "" {
|
|
name = printer.record.PrinterID
|
|
}
|
|
heater := temperatureHeaterDisplayName(selection.Heater)
|
|
lines := []string{
|
|
fmt.Sprintf("Printer: %s", name),
|
|
fmt.Sprintf("Action: Set %s target", heater),
|
|
fmt.Sprintf("Target: %s %.1f°C", heater, selection.Target),
|
|
"Snapshot: review the bed before confirming",
|
|
}
|
|
if printer.health != nil && printer.health.PrintStatus != nil {
|
|
if state := strings.TrimSpace(printer.health.PrintStatus.State); state != "" {
|
|
lines = append(lines, fmt.Sprintf("Current state: %s", state))
|
|
}
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
func formatJobSelectionLabel(filename, status string) string {
|
|
filename = strings.TrimSpace(filename)
|
|
status = strings.TrimSpace(status)
|
|
if filename == "" {
|
|
return ""
|
|
}
|
|
if status == "" {
|
|
return filename
|
|
}
|
|
return fmt.Sprintf("%s (%s)", filename, status)
|
|
}
|
|
|
|
type telegramPrinterTarget struct {
|
|
record printerSettingsRecord
|
|
health *protocol.Health
|
|
}
|
|
|
|
func (b *telegramBot) resolvePrinter(query string) (telegramPrinterTarget, error) {
|
|
query = strings.TrimSpace(query)
|
|
records := b.server.printerSettings.list()
|
|
if query == "" {
|
|
if len(records) == 1 {
|
|
return b.resolvePrinterByRecord(records[0]), nil
|
|
}
|
|
connected := b.connectedPrinters()
|
|
if len(connected) == 1 {
|
|
return connected[0], nil
|
|
}
|
|
if len(records) == 0 {
|
|
return telegramPrinterTarget{}, fmt.Errorf("no printers are known yet")
|
|
}
|
|
return telegramPrinterTarget{}, fmt.Errorf("specify a printer id, for example: /status %s", records[0].PrinterID)
|
|
}
|
|
for _, record := range records {
|
|
if strings.EqualFold(record.PrinterID, query) || strings.EqualFold(record.DisplayName, query) {
|
|
return b.resolvePrinterByRecord(record), nil
|
|
}
|
|
}
|
|
return telegramPrinterTarget{}, fmt.Errorf("unknown printer %q", query)
|
|
}
|
|
|
|
func (b *telegramBot) resolvePrinterByRecord(record printerSettingsRecord) telegramPrinterTarget {
|
|
target := telegramPrinterTarget{record: record}
|
|
b.server.tunnelsMu.RLock()
|
|
t := b.server.tunnels[record.PrinterID]
|
|
b.server.tunnelsMu.RUnlock()
|
|
if t != nil {
|
|
t.healthMu.RLock()
|
|
target.health = t.health
|
|
t.healthMu.RUnlock()
|
|
}
|
|
if target.health == nil {
|
|
target.health = &protocol.Health{}
|
|
}
|
|
return target
|
|
}
|
|
|
|
func (b *telegramBot) connectedPrinters() []telegramPrinterTarget {
|
|
b.server.tunnelsMu.RLock()
|
|
defer b.server.tunnelsMu.RUnlock()
|
|
targets := make([]telegramPrinterTarget, 0, len(b.server.tunnels))
|
|
for printerID, t := range b.server.tunnels {
|
|
record, ok := b.server.printerSettings.snapshot(printerID)
|
|
if !ok {
|
|
record = printerSettingsRecord{PrinterID: printerID}
|
|
}
|
|
target := telegramPrinterTarget{record: record}
|
|
if t != nil {
|
|
t.healthMu.RLock()
|
|
target.health = t.health
|
|
t.healthMu.RUnlock()
|
|
}
|
|
targets = append(targets, target)
|
|
}
|
|
return targets
|
|
}
|
|
|
|
func (b *telegramBot) printerSelectionRecords() []printerSettingsRecord {
|
|
if b == nil || b.server == nil {
|
|
return nil
|
|
}
|
|
records := b.server.printerSettings.list()
|
|
seen := make(map[string]struct{}, len(records))
|
|
out := make([]printerSettingsRecord, 0, len(records))
|
|
for _, record := range records {
|
|
printerID := strings.TrimSpace(record.PrinterID)
|
|
if printerID == "" {
|
|
continue
|
|
}
|
|
seen[printerID] = struct{}{}
|
|
out = append(out, record)
|
|
}
|
|
for _, target := range b.connectedPrinters() {
|
|
printerID := strings.TrimSpace(target.record.PrinterID)
|
|
if printerID == "" {
|
|
continue
|
|
}
|
|
if _, ok := seen[printerID]; ok {
|
|
continue
|
|
}
|
|
seen[printerID] = struct{}{}
|
|
out = append(out, target.record)
|
|
}
|
|
sort.SliceStable(out, func(i, j int) bool {
|
|
return strings.ToLower(strings.TrimSpace(out[i].PrinterID)) < strings.ToLower(strings.TrimSpace(out[j].PrinterID))
|
|
})
|
|
return out
|
|
}
|
|
|
|
func (b *telegramBot) printerRecordFromCallback(printerID string) (printerSettingsRecord, bool) {
|
|
printerID = strings.TrimSpace(printerID)
|
|
if printerID == "" || b == nil || b.server == nil || b.server.printerSettings == nil {
|
|
return printerSettingsRecord{}, false
|
|
}
|
|
record, ok := b.server.printerSettings.snapshot(printerID)
|
|
if !ok {
|
|
return printerSettingsRecord{}, false
|
|
}
|
|
return record, true
|
|
}
|
|
|
|
func telegramHelpMessage() string {
|
|
return strings.Join([]string{
|
|
"Commands:",
|
|
"/help - show this message",
|
|
"/printers - list known printers",
|
|
"/status [printer] - show the current print status, temperatures, and fans",
|
|
"/set [printer] <extruder|bed> <temp> - set a heater target",
|
|
"/print [printer] - list recent jobs and choose one to print",
|
|
"/jobs [printer] - list recent jobs",
|
|
"/camera [printer] - pick a camera and send a snapshot",
|
|
"/reprint [printer] - restart the last printable job",
|
|
}, "\n")
|
|
}
|
|
|
|
func (b *telegramBot) buildPrintersMessage() string {
|
|
records := b.server.printerSettings.list()
|
|
if len(records) == 0 {
|
|
return "No printers are known yet."
|
|
}
|
|
lines := []string{"Printers:"}
|
|
for _, record := range records {
|
|
lines = append(lines, b.formatPrinterSummary(record))
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
func (b *telegramBot) buildPrinterStatusMessage(target telegramPrinterTarget) string {
|
|
name := strings.TrimSpace(target.record.DisplayName)
|
|
if name == "" {
|
|
name = target.record.PrinterID
|
|
}
|
|
lines := []string{
|
|
fmt.Sprintf("Printer: %s", name),
|
|
fmt.Sprintf("Printer ID: %s", target.record.PrinterID),
|
|
}
|
|
if target.health == nil || target.health.PrintStatus == nil {
|
|
lines = append(lines, "Connected: no")
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
lines = append(lines, "Connected: yes")
|
|
status := target.health.PrintStatus
|
|
if state := strings.TrimSpace(status.State); state != "" {
|
|
lines = append(lines, fmt.Sprintf("State: %s", state))
|
|
}
|
|
if fn := strings.TrimSpace(status.Filename); fn != "" {
|
|
lines = append(lines, fmt.Sprintf("File: %s", fn))
|
|
}
|
|
if layer := formatTelegramLayer(status.CurrentLayer, status.TotalLayer); layer != "" {
|
|
lines = append(lines, fmt.Sprintf("Layer: %s", layer))
|
|
}
|
|
if progress := status.Progress; progress > 0 {
|
|
lines = append(lines, fmt.Sprintf("Progress: %.0f%%", progress*100))
|
|
}
|
|
if duration := formatTelegramDuration(status.PrintDuration); duration != "" {
|
|
lines = append(lines, fmt.Sprintf("Printed: %s", duration))
|
|
}
|
|
if remaining := formatTelegramDuration(status.EstimatedTimeRemaining); remaining != "" {
|
|
lines = append(lines, fmt.Sprintf("Remaining: %s", remaining))
|
|
}
|
|
if message := strings.TrimSpace(status.Message); message != "" {
|
|
lines = append(lines, fmt.Sprintf("Message: %s", message))
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
func (b *telegramBot) buildPrinterStatusMessageWithLiveData(target telegramPrinterTarget, liveStatus map[string]any) string {
|
|
base := b.buildPrinterStatusMessage(target)
|
|
if len(liveStatus) == 0 {
|
|
return base
|
|
}
|
|
temperatureLines := temperatureObjectSummary(liveStatus)
|
|
fanLines := fanObjectSummary(liveStatus)
|
|
if len(temperatureLines) == 0 && len(fanLines) == 0 {
|
|
return base
|
|
}
|
|
lines := []string{base}
|
|
if len(temperatureLines) > 0 {
|
|
lines = append(lines, "Temperatures:")
|
|
lines = append(lines, temperatureLines...)
|
|
}
|
|
if len(fanLines) > 0 {
|
|
lines = append(lines, "Fans:")
|
|
lines = append(lines, fanLines...)
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
func (b *telegramBot) formatPrinterSummary(record printerSettingsRecord) string {
|
|
name := strings.TrimSpace(record.DisplayName)
|
|
if name == "" {
|
|
name = record.PrinterID
|
|
}
|
|
b.server.tunnelsMu.RLock()
|
|
t := b.server.tunnels[record.PrinterID]
|
|
b.server.tunnelsMu.RUnlock()
|
|
if t == nil {
|
|
return fmt.Sprintf("- %s (%s): disconnected", name, record.PrinterID)
|
|
}
|
|
t.healthMu.RLock()
|
|
health := t.health
|
|
t.healthMu.RUnlock()
|
|
state := "connected"
|
|
if health != nil && health.PrintStatus != nil && strings.TrimSpace(health.PrintStatus.State) != "" {
|
|
state = strings.TrimSpace(health.PrintStatus.State)
|
|
}
|
|
layer := ""
|
|
if health != nil && health.PrintStatus != nil {
|
|
layer = formatTelegramLayer(health.PrintStatus.CurrentLayer, health.PrintStatus.TotalLayer)
|
|
}
|
|
if layer != "" {
|
|
return fmt.Sprintf("- %s (%s): %s, layer %s", name, record.PrinterID, state, layer)
|
|
}
|
|
return fmt.Sprintf("- %s (%s): %s", name, record.PrinterID, state)
|
|
}
|
|
|
|
func parseTelegramCommand(text string) (string, string) {
|
|
text = strings.TrimSpace(text)
|
|
if text == "" || !strings.HasPrefix(text, "/") {
|
|
return "", ""
|
|
}
|
|
fields := strings.Fields(text)
|
|
if len(fields) == 0 {
|
|
return "", ""
|
|
}
|
|
command := strings.TrimPrefix(fields[0], "/")
|
|
if idx := strings.Index(command, "@"); idx >= 0 {
|
|
command = command[:idx]
|
|
}
|
|
command = strings.ToLower(strings.TrimSpace(command))
|
|
args := strings.TrimSpace(strings.TrimPrefix(text, fields[0]))
|
|
return command, args
|
|
}
|
|
|
|
func parseTelegramTemperatureSetArgs(args string) (string, string, float64, error) {
|
|
fields := strings.Fields(strings.TrimSpace(args))
|
|
if len(fields) < 2 {
|
|
return "", "", 0, fmt.Errorf("usage: /set [printer] <extruder|bed> <temp>")
|
|
}
|
|
var printerQuery string
|
|
var heater string
|
|
var targetText string
|
|
switch len(fields) {
|
|
case 2:
|
|
heater = fields[0]
|
|
targetText = fields[1]
|
|
default:
|
|
printerQuery = strings.Join(fields[:len(fields)-2], " ")
|
|
heater = fields[len(fields)-2]
|
|
targetText = fields[len(fields)-1]
|
|
}
|
|
target, err := strconv.ParseFloat(targetText, 64)
|
|
if err != nil {
|
|
return "", "", 0, fmt.Errorf("temperature must be a number")
|
|
}
|
|
heaterName, err := normalizeTemperatureHeater(heater)
|
|
if err != nil {
|
|
return "", "", 0, err
|
|
}
|
|
return printerQuery, heaterName, target, nil
|
|
}
|
|
|
|
func normalizeTemperatureHeater(value string) (string, error) {
|
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
|
case "extruder", "nozzle", "hotend":
|
|
return "extruder", nil
|
|
case "bed", "heatbed", "heater_bed", "heatedbed":
|
|
return "heater_bed", nil
|
|
default:
|
|
return "", fmt.Errorf("unknown heater %q; use extruder or bed", value)
|
|
}
|
|
}
|
|
|
|
func temperatureHeaterDisplayName(value string) string {
|
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
|
case "heater_bed":
|
|
return "bed"
|
|
default:
|
|
return strings.TrimSpace(value)
|
|
}
|
|
}
|