Files
KlipperAnywhere/cmd/server/notifications.go
T
2026-05-14 02:27:26 +01:00

541 lines
17 KiB
Go

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