pushraker 0.2.2__tar.gz → 0.2.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {pushraker-0.2.2/src/pushraker.egg-info → pushraker-0.2.5}/PKG-INFO +1 -1
  2. {pushraker-0.2.2 → pushraker-0.2.5}/pyproject.toml +1 -1
  3. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/__init__.py +1 -1
  4. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/component.py +105 -13
  5. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/printers/__init__.py +7 -0
  6. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/printers/snapmaker_u1.py +19 -1
  7. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/settings.py +19 -72
  8. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/web/index.html +164 -58
  9. {pushraker-0.2.2 → pushraker-0.2.5/src/pushraker.egg-info}/PKG-INFO +1 -1
  10. {pushraker-0.2.2 → pushraker-0.2.5}/tests/test_pushraker.py +76 -2
  11. {pushraker-0.2.2 → pushraker-0.2.5}/tests/test_settings.py +13 -20
  12. {pushraker-0.2.2 → pushraker-0.2.5}/LICENSE +0 -0
  13. {pushraker-0.2.2 → pushraker-0.2.5}/README.md +0 -0
  14. {pushraker-0.2.2 → pushraker-0.2.5}/setup.cfg +0 -0
  15. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/__main__.py +0 -0
  16. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/discord.py +0 -0
  17. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/email_html.py +0 -0
  18. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/images.py +0 -0
  19. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker/klipper/pushraker.cfg +0 -0
  20. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker.egg-info/SOURCES.txt +0 -0
  21. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker.egg-info/dependency_links.txt +0 -0
  22. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker.egg-info/requires.txt +0 -0
  23. {pushraker-0.2.2 → pushraker-0.2.5}/src/pushraker.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pushraker
3
- Version: 0.2.2
3
+ Version: 0.2.5
4
4
  Summary: Push notifications for Klipper printers: a Moonraker component with pictures, sent through Apprise (ntfy, Pushover, Telegram, Discord, webhooks, email)
5
5
  Author: noon92
6
6
  License-Expression: GPL-3.0-or-later
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pushraker"
7
- version = "0.2.2"
7
+ version = "0.2.5"
8
8
  description = "Push notifications for Klipper printers: a Moonraker component with pictures, sent through Apprise (ntfy, Pushover, Telegram, Discord, webhooks, email)"
9
9
  readme = "README.md"
10
10
  license = "GPL-3.0-or-later"
@@ -4,4 +4,4 @@
4
4
 
5
5
  """Push notifications for Klipper printers, as a Moonraker component."""
6
6
 
7
- __version__ = "0.2.2"
7
+ __version__ = "0.2.5"
@@ -102,7 +102,7 @@ REMOTE_METHOD = "pushraker"
102
102
  OLD_REMOTE_METHOD = "push_notification"
103
103
  MILESTONES = (25, 50, 75)
104
104
  ROW_IDS = (
105
- "started", "layer_started", "first_layer", "progress_25", "progress_50", "progress_75",
105
+ "started", "preprint_done", "layer_started", "first_layer", "progress_25", "progress_50", "progress_75",
106
106
  "status_report",
107
107
  "paused", "file_pause", "resumed", "object_complete", "complete", "cancelled",
108
108
  "calibration",
@@ -115,6 +115,7 @@ ROW_IDS = (
115
115
  SPOOLMAN_ROWS = ("filament_short", "filament_low", "spool_switch")
116
116
  TITLES = {
117
117
  "started": "▶️ {name} started",
118
+ "preprint_done": "▶️ {name} pre-print calibrations complete",
118
119
  "layer_started": "🎬 {name} first layer started",
119
120
  "first_layer": "🔍 {name} {ordinal} layer complete",
120
121
  "progress": "⏳ {name} {pct}%",
@@ -254,7 +255,7 @@ NOTIFY_TYPES = {"complete": "success", "object_complete": "success",
254
255
  FILE_CAP = 30
255
256
  # Emails about one print go in one thread (see _email_prepare). Faults
256
257
  # join it while printing and this long after the print ended.
257
- THREAD_ROWS = ("started", "layer_started", "first_layer",
258
+ THREAD_ROWS = ("started", "preprint_done", "layer_started", "first_layer",
258
259
  "progress_25", "progress_50",
259
260
  "progress_75", "status_report", "paused", "file_pause", "resumed", "object_complete",
260
261
  "complete", "cancelled",
@@ -268,6 +269,10 @@ PTC_FIELDS = ["extruder_map_table", "filament_spool_id", "extruders_used",
268
269
  "filament_exist", "filament_vendor", "filament_type",
269
270
  "filament_sub_type", "filament_color_rgba",
270
271
  "filament_color_multi"]
272
+ # The pre-print calibrations chosen for a job (printers that have them)
273
+ PREPRINT_FIELDS = ["auto_bed_leveling", "flow_calibrate",
274
+ "flow_calib_extruders", "shaper_calibrate",
275
+ "extruders_used"]
271
276
  # The printer refills only from a toolhead with the same nozzle
272
277
  # (extruders: printers.py)
273
278
  NOZZLE_FIELDS = ["nozzle_diameter", "nozzle_volume_type"]
@@ -290,7 +295,8 @@ SEND_GAP = {"ntfy": 2.} # seconds before each retry of a failed send
290
295
  # notification an hour late is noise. Faults and complete never expire.
291
296
  URGENT_ROWS = ("error", "warning", "shutdown", "power_loss",
292
297
  "chamber_fault")
293
- EXPIRING_ROWS = ("started", "layer_started", "first_layer", "progress_25",
298
+ EXPIRING_ROWS = ("started", "preprint_done", "layer_started", "first_layer",
299
+ "progress_25",
294
300
  "progress_50", "progress_75", "object_complete",
295
301
  "chamber_waiting", "chamber_reached", "filament_change")
296
302
  STATUS_EXPIRY = 300.
@@ -887,6 +893,12 @@ class PushNotifications:
887
893
  self._job_done_sent = False
888
894
  self._first_layer_sent = False
889
895
  self._layer_started_sent = False
896
+ # Pre-print calibrations of this job: their names (for the started
897
+ # notification), the ones still to run, the one running now
898
+ self._pp_names: List[str] = []
899
+ self._pp_pending: set = set()
900
+ self._pp_running: Optional[Tuple[str, Optional[int]]] = None
901
+ self._pp_sent = True
890
902
  self._milestones_sent: Set[int] = set()
891
903
  # Print time (which stops while paused) the next status report is
892
904
  # due at; None until the job's first status update sets it
@@ -1001,16 +1013,12 @@ class PushNotifications:
1001
1013
  spoolman = re.sub(r"/api(/v\d+)?/?$", "", url.rstrip("/"))
1002
1014
  except Exception:
1003
1015
  spoolman = ""
1004
- try:
1005
- ts = await self.eventloop.run_in_thread(cfgmod.tailscale_info)
1006
- except Exception:
1007
- ts = ("", "")
1008
1016
  return cfgmod.Env(cameras=cams, spoolman_url=spoolman,
1009
- local_ip=cfgmod.local_ip(), tailscale=ts,
1010
1017
  error_index_url=self.error_index_url,
1011
1018
  name=self.store.default_name if self.store
1012
1019
  else self.name,
1013
- rows_unavailable=self.printer.rows_unavailable)
1020
+ rows_unavailable=self.printer.rows_unavailable,
1021
+ preprint=bool(self.printer.preprint_calibrations))
1014
1022
 
1015
1023
  async def _reload(self, why: str) -> None:
1016
1024
  """Read pushraker.conf and apply it. Settings that don't pass
@@ -1959,6 +1967,7 @@ class PushNotifications:
1959
1967
  float(ps.get("print_duration") or 0.) > RECOVERY_MIN_TIME
1960
1968
  or progress >= RECOVERY_SURE_PROGRESS)
1961
1969
  self._thread_start(filename, recovered)
1970
+ self._preprint_seed(recovered)
1962
1971
  if recovered:
1963
1972
  # Snapmaker resumes a power-loss print as a new job
1964
1973
  self._spawn(self._send(
@@ -1970,7 +1979,8 @@ class PushNotifications:
1970
1979
  self._lines(shown(filename),
1971
1980
  self._slicer_estimate(filename),
1972
1981
  self._queue_line(filename, starting=True),
1973
- self._pauses_line()),
1982
+ self._pauses_line(),
1983
+ self._preprint_line()),
1974
1984
  filename=filename))
1975
1985
  # After the started notification has taken its place in the
1976
1986
  # queues, so filament warnings always arrive after it
@@ -2047,7 +2057,9 @@ class PushNotifications:
2047
2057
  self._job_done_sent = False
2048
2058
  if query:
2049
2059
  state = await self._query(
2050
- {"print_stats": ["info"], "virtual_sdcard": ["file_position"]})
2060
+ {"print_stats": ["info"], "virtual_sdcard": ["file_position"],
2061
+ **({"print_task_config": PREPRINT_FIELDS}
2062
+ if self.printer.preprint_calibrations else {})})
2051
2063
  for obj in self._status:
2052
2064
  self._status[obj].update(state.get(obj) or {})
2053
2065
  self._gcode_bytes = self._get_gcode_bytes(filename)
@@ -2679,6 +2691,7 @@ class PushNotifications:
2679
2691
  self._idle_was = idle
2680
2692
  if "machine_state_manager" in data:
2681
2693
  self._track_calibration()
2694
+ self._track_preprint()
2682
2695
  if "filament_exist" in (data.get("print_task_config") or {}):
2683
2696
  self._track_filament_change()
2684
2697
  if ACE_OBJECT in data:
@@ -2710,6 +2723,12 @@ class PushNotifications:
2710
2723
  self._by_object = False
2711
2724
  logging.info("[pushraker] no object markers in %s: "
2712
2725
  "reported as one job", shown(filename))
2726
+ if not self._pp_sent:
2727
+ # Layer 1 began: the start routine is over, even if a chosen
2728
+ # calibration was skipped (a toolhead already calibrated)
2729
+ layer = (ps.get("info") or {}).get("current_layer")
2730
+ if layer is not None and int(layer) >= 1:
2731
+ self._preprint_done(filename)
2713
2732
  if "layer_started" in self.rows and not self._layer_started_sent:
2714
2733
  # Layer 1 begins once the start routine (homing, bed mesh,
2715
2734
  # flow calibration) is over: time to watch the first layer
@@ -2843,6 +2862,79 @@ class PushNotifications:
2843
2862
  for p in out))
2844
2863
  return out
2845
2864
 
2865
+ # ---- pre-print calibrations ----------------------------------------
2866
+
2867
+ def _preprint_seed(self, recovered: bool) -> None:
2868
+ """At the job's start: which pre-print calibrations were chosen
2869
+ (print_task_config), and so which runs to wait for."""
2870
+ self._pp_names, self._pp_pending = [], set()
2871
+ self._pp_running, self._pp_sent = None, True
2872
+ cal = self.printer.preprint_calibrations
2873
+ if not cal or recovered:
2874
+ return
2875
+ ptc = self._status["print_task_config"]
2876
+ used = list(ptc.get("extruders_used") or [])
2877
+ which = list(ptc.get("flow_calib_extruders") or [])
2878
+ for flag, name in cal.items():
2879
+ if not ptc.get(flag):
2880
+ continue
2881
+ self._pp_names.append(name)
2882
+ per_tool = sorted({i for c, (f, i) in
2883
+ self.printer.preprint_codes.items()
2884
+ if f == flag and i is not None})
2885
+ if not per_tool:
2886
+ self._pp_pending.add((flag, None))
2887
+ continue
2888
+ for i in per_tool:
2889
+ if (i >= len(which) or which[i]) and \
2890
+ (i >= len(used) or used[i]):
2891
+ self._pp_pending.add((flag, i))
2892
+ self._pp_sent = not self._pp_names
2893
+
2894
+ def _preprint_line(self) -> str:
2895
+ if not self._pp_names:
2896
+ return ""
2897
+ # A blank line before it unless the pauses line has one
2898
+ return ("" if self._job_pauses else "\n") + \
2899
+ "📐 Pre-print calibrations selected: " + \
2900
+ ", ".join(self._pp_names) + "."
2901
+
2902
+ def _track_preprint(self) -> None:
2903
+ """During the job's start routine: each chosen calibration's
2904
+ action_code while it runs, back to idle when done; when none is
2905
+ left, they are complete (also when layer 1 begins first)."""
2906
+ if self._pp_sent or not self._job_active:
2907
+ return
2908
+ try:
2909
+ action = int(self._status["machine_state_manager"]
2910
+ .get("action_code") or 0)
2911
+ except (TypeError, ValueError):
2912
+ return
2913
+ step = self.printer.preprint_codes.get(action)
2914
+ if step is not None:
2915
+ self._pp_running = step
2916
+ return
2917
+ if self._pp_running is None or action != 0:
2918
+ return
2919
+ self._pp_pending.discard(self._pp_running)
2920
+ self._pp_running = None
2921
+ if not self._pp_pending:
2922
+ self._preprint_done(self._job_filename)
2923
+
2924
+ def _preprint_done(self, filename: str) -> None:
2925
+ self._pp_sent = True
2926
+ if cfgmod.PREPRINT_ROW not in self.rows:
2927
+ return
2928
+ names = self._pp_names
2929
+ done = names[0] if len(names) == 1 else \
2930
+ ", ".join(names[:-1]) + " and " + names[-1]
2931
+ self._spawn(self._send(
2932
+ cfgmod.PREPRINT_ROW, self._title("preprint_done"),
2933
+ self._lines(shown(filename),
2934
+ f"{done} done. Starting the print job.",
2935
+ self._time_left()),
2936
+ filename=filename))
2937
+
2846
2938
  def _pauses_line(self) -> str:
2847
2939
  """For the started notification: how many pauses the file has."""
2848
2940
  ps = self._job_pauses
@@ -2854,8 +2946,8 @@ class PushNotifications:
2854
2946
  where = (f" (layer {layers[0]})" if len(layers) == 1 else
2855
2947
  " (layers " + ", ".join(str(n) for n in layers[:-1])
2856
2948
  + f" and {layers[-1]})")
2857
- return ("\nPrint job contains a pause" if len(ps) == 1 else
2858
- f"\nPrint job contains {len(ps)} pauses") + where + "."
2949
+ return ("\n⏸️ Print job contains a pause" if len(ps) == 1 else
2950
+ f"\n⏸️ Print job contains {len(ps)} pauses") + where + "."
2859
2951
 
2860
2952
  def _file_pause(self, position: Any) -> Optional[int]:
2861
2953
  """Index of the file's pause the print job stopped at, if the file
@@ -50,6 +50,13 @@ class Printer:
50
50
  # The printer's own toolhead map and refill (print_task_config): with
51
51
  # it, runouts can be refilled from another toolhead
52
52
  toolhead_map = False
53
+ # Pre-print calibrations a print job can be started with (chosen on
54
+ # the printer when the job starts): the flag in print_task_config ->
55
+ # its name; and the action_code values (machine_state_manager) while
56
+ # each runs, -> (the flag, the toolhead index for per-toolhead ones,
57
+ # else None). Empty: the printer has none (no line, no checkbox)
58
+ preprint_calibrations: Dict[str, str] = {}
59
+ preprint_codes: Dict[int, Tuple[str, Optional[int]]] = {}
53
60
  # The print-end snapshot lift keeps Z at or below this; 0 means 5 mm
54
61
  # under the printer's axis maximum (the macro file reads it)
55
62
  lift_ceiling = 0
@@ -5,7 +5,7 @@
5
5
  """The Snapmaker U1 (with the extended firmware): what its Klipper adds
6
6
  beyond the standard objects. The firmware-side harness (the install step,
7
7
  the nginx alias, the Firmware Config entry) lives in the firmware's own
8
- repository, overlay 42-feature-notifications."""
8
+ repository, overlay 42-feature-pushraker."""
9
9
 
10
10
  from __future__ import annotations
11
11
  from typing import Sequence
@@ -36,6 +36,24 @@ class SnapmakerU1(Printer):
36
36
  "/home/lava/printer_data/config/snapmaker/pl_print_file_env.json",
37
37
  )
38
38
  toolhead_map = True
39
+ # Chosen on the screen when a print job starts (print_task_config.py);
40
+ # while each runs, machine_state_manager's action_code is BED_PREHEATING
41
+ # (257), BED_PRESCANNING (258), BED_LEVELING (256),
42
+ # EXTRUDER<n>_FLOW_CALIBRATING (320 + toolhead) or SHAPER_CALIBRATING
43
+ # (384), back to IDLE (0) after each (seen on a U1: 257, 258, 256, 0;
44
+ # 323, 0)
45
+ preprint_calibrations = {
46
+ "auto_bed_leveling": "Bed levelling",
47
+ "flow_calibrate": "Extrusion flow calibration (pressure advance)",
48
+ "shaper_calibrate": "Input shaper calibration",
49
+ }
50
+ preprint_codes = {
51
+ 256: ("auto_bed_leveling", None), 257: ("auto_bed_leveling", None),
52
+ 258: ("auto_bed_leveling", None),
53
+ 320: ("flow_calibrate", 0), 321: ("flow_calibrate", 1),
54
+ 322: ("flow_calibrate", 2), 323: ("flow_calibrate", 3),
55
+ 384: ("shaper_calibrate", None),
56
+ }
39
57
  rows_unavailable: Sequence[str] = ()
40
58
  # The stock PRINT_END / CANCEL_PRINT raise Z by 5 mm below 265 mm; the
41
59
  # lift stays inside that
@@ -19,8 +19,6 @@ import io
19
19
  import json
20
20
  import os
21
21
  import re
22
- import socket
23
- import subprocess
24
22
  import urllib.error
25
23
  import urllib.request
26
24
  from typing import Any, Dict, List, Optional, Sequence, Tuple
@@ -118,6 +116,9 @@ OBJECT_ROW = "object_complete"
118
116
  # A pause the print job's file asks for is sent with the Paused row's
119
117
  # destinations at the highest priority: the file wants something from you
120
118
  FILE_PAUSE_ROW = "file_pause"
119
+ # Pre-print calibrations done (printers that have them): sent with the
120
+ # Print started row's settings, when its checkbox is on
121
+ PREPRINT_ROW = "preprint_done"
121
122
  ERROR_ROWS = ("error", "warning", "shutdown")
122
123
  # Rows that read Spoolman (the first two need it; the switch works without)
123
124
  SPOOLMAN_ROWS = ("filament_short", "filament_low", "spool_switch")
@@ -168,7 +169,7 @@ SECRET_FIELDS = ("secret", "email_password", "webhook_url")
168
169
  INT_FIELDS = ("layers_complete", "email_port", "filament_low_percent",
169
170
  "filament_low_grams", "driver_temp", "report_interval")
170
171
  BOOL_FIELDS = ("enabled", "push_enabled", "email_enabled", "webhook_enabled",
171
- "filament_unknown")
172
+ "filament_unknown", "preprint_done")
172
173
  # Settings the form fills in for common providers
173
174
  EMAIL_PRESETS = {
174
175
  "gmail": {"label": "Gmail", "host": "smtp.gmail.com", "port": 587,
@@ -194,25 +195,24 @@ class Env:
194
195
  the component fetches (absolute), "stream": the live
195
196
  view's path or URL for the notification's link}
196
197
  spoolman_url Spoolman's base URL when Moonraker has [spoolman], else ""
197
- local_ip the printer's LAN address, for the printer URL buttons
198
- tailscale (MagicDNS name, IPv4) when Tailscale runs, else ("", "")
199
198
  error_index_url the printer maker's error-code index, linked from
200
199
  fault notifications ("" for none)
201
200
  name the printer's default name
202
201
  rows_unavailable rows the printer can't produce (off by default and
203
202
  left off the page unless turned on in pushraker.conf)
203
+ preprint the printer has pre-print calibrations (the Print
204
+ started row's checkbox)
204
205
  """
205
206
 
206
207
  def __init__(self, cameras: Optional[Dict[str, Dict[str, str]]] = None,
207
- spoolman_url: str = "", local_ip: str = "",
208
- tailscale: Tuple[str, str] = ("", ""),
208
+ spoolman_url: str = "",
209
209
  error_index_url: str = "", name: str = "Printer",
210
- rows_unavailable: Sequence[str] = ()) -> None:
210
+ rows_unavailable: Sequence[str] = (),
211
+ preprint: bool = False) -> None:
211
212
  self.cameras = cameras or {}
213
+ self.preprint = preprint
212
214
  self.rows_unavailable = set(rows_unavailable)
213
215
  self.spoolman_url = spoolman_url.rstrip("/")
214
- self.local_ip = local_ip
215
- self.tailscale = tailscale
216
216
  self.error_index_url = error_index_url
217
217
  self.name = name
218
218
 
@@ -265,6 +265,9 @@ def _defaults(name: str) -> Dict[str, Any]:
265
265
  "filament_low_percent": 10,
266
266
  "filament_low_grams": 50,
267
267
  "filament_unknown": True,
268
+ # Under Print started: also notify when the pre-print calibrations
269
+ # chosen for the job are done
270
+ "preprint_done": True,
268
271
  "driver_temp": 105, # °C, X or Y stepper driver (row: driver_hot)
269
272
  "report_interval": 30, # minutes of print time between status reports
270
273
  "email_enabled": False,
@@ -617,15 +620,6 @@ def validate(data: Dict[str, Any], current: Dict[str, Any],
617
620
  raise ValueError("host or port")
618
621
  except ValueError:
619
622
  raise ConfigError("Printer URL must look like http://100.64.0.1")
620
- if s["printer_url"] and s["provider"] == "telegram" and s["push_enabled"]:
621
- host = urlparse(printer_root(s, env)).hostname or ""
622
- if "." not in host and ":" not in host:
623
- # Telegram drops text links whose host has no dot; the Tailscale
624
- # name was already replaced by the IP in printer_root
625
- raise ConfigError("Telegram doesn't link to a name without a "
626
- "dot, such as http://u1. Use the Tailscale "
627
- "name (Use Tailscale) or an IP address.")
628
-
629
623
  validate_email(s)
630
624
  if s["webhook_enabled"]:
631
625
  try:
@@ -844,56 +838,9 @@ def camera_live_url(s: Dict[str, Any], env: Env) -> str:
844
838
 
845
839
 
846
840
  def printer_root(s: Dict[str, Any], env: Optional[Env]) -> str:
847
- """The Printer URL without a trailing slash, as sent: for Telegram the
848
- Tailscale name becomes the Tailscale IP, because Telegram drops text
849
- links whose host has no dot (the text stays, the link is gone)."""
850
- root = s["printer_url"].rstrip("/")
851
- if env and s["provider"] == "telegram" and s["push_enabled"]:
852
- host, ip = env.tailscale
853
- try:
854
- u = urlparse(root)
855
- if host and ip and (u.hostname or "").lower() == host.lower():
856
- port = f":{u.port}" if u.port else ""
857
- root = u._replace(netloc=f"{ip}{port}").geturl()
858
- except ValueError:
859
- pass
860
- return root
861
-
862
-
863
- def local_ip() -> str:
864
- """The printer's LAN address (the source address of its default route)."""
865
- try:
866
- with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
867
- sock.connect(("192.0.2.1", 9)) # no packet is sent
868
- return sock.getsockname()[0]
869
- except OSError:
870
- return ""
871
-
872
-
873
- def tailscale_info(binary: str = "tailscale") -> Tuple[str, str]:
874
- """(MagicDNS name, IPv4) of this machine, if Tailscale is installed
875
- and running; ("", "") otherwise."""
876
- for path in (binary, "/usr/local/bin/tailscale", "/usr/bin/tailscale"):
877
- try:
878
- out = subprocess.run([path, "status", "--json"],
879
- capture_output=True, text=True, timeout=5)
880
- st = json.loads(out.stdout)
881
- break
882
- except (OSError, ValueError, subprocess.SubprocessError):
883
- continue
884
- else:
885
- return "", ""
886
- if st.get("BackendState") != "Running":
887
- return "", ""
888
- me = st.get("Self") or {}
889
- dns = (me.get("DNSName") or "").rstrip(".")
890
- # The short MagicDNS name resolves on devices with MagicDNS enabled
891
- host = dns.split(".")[0] if dns else (me.get("HostName") or "")
892
- ip = next((a for a in me.get("TailscaleIPs") or [] if ":" not in a), "")
893
- return host, ip
894
-
841
+ """The Printer URL without a trailing slash, as sent."""
842
+ return s["printer_url"].rstrip("/")
895
843
 
896
- # ---- Apprise URLs --------------------------------------------------------
897
844
 
898
845
  def links(s: Dict[str, Any], rid: str, env: Env) -> List[Tuple[str, str]]:
899
846
  """(title, url) buttons for a notification."""
@@ -1120,7 +1067,9 @@ def render_options(s: Dict[str, Any], env: Env) -> Dict[str, str]:
1120
1067
  # The object-complete notification follows the Print complete row
1121
1068
  for name in ([rid, OBJECT_ROW] if rid == "complete"
1122
1069
  and s["complete_objects"] == "each" else
1123
- [rid, FILE_PAUSE_ROW] if rid == "paused" else [rid]):
1070
+ [rid, FILE_PAUSE_ROW] if rid == "paused" else
1071
+ [rid, PREPRINT_ROW] if rid == "started"
1072
+ and s["preprint_done"] and env.preprint else [rid]):
1124
1073
  if rid in push:
1125
1074
  url = row_url(s, rid, "max" if name == FILE_PAUSE_ROW
1126
1075
  else s["rows"][rid]["priority"], env)
@@ -1257,14 +1206,12 @@ def public_view(s: Dict[str, Any], env: Env, busy: bool,
1257
1206
  for r in ROWS],
1258
1207
  "email_presets": EMAIL_PRESETS,
1259
1208
  "spoolman": bool(env.spoolman_url),
1209
+ "preprint": env.preprint,
1260
1210
  "priorities": PRIORITIES,
1261
1211
  "providers": PROVIDERS,
1262
1212
  "cameras": {name: {"snapshot": bool(c.get("snapshot")),
1263
1213
  "stream": bool(c.get("stream"))}
1264
1214
  for name, c in env.cameras.items()},
1265
- "local_ip": env.local_ip,
1266
- "tailscale_host": env.tailscale[0],
1267
- "tailscale_ip": env.tailscale[1],
1268
1215
  "busy": busy,
1269
1216
  "default_name": env.name,
1270
1217
  "stored_error": stored_error(s, env),
@@ -29,20 +29,36 @@
29
29
  .btn-primary:hover:not(:disabled) { background: #29b6f6; }
30
30
  .btn-secondary { background: #555; color: #fff; }
31
31
  .btn-secondary:hover:not(:disabled) { background: #666; }
32
- .pr-actions { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; position: sticky; bottom: 0; background: var(--bg); padding: 12px 0; }
32
+ .pr-actions { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; position: sticky; bottom: 0; background: var(--bg); padding: 12px 10px; }
33
33
  .pr-status { font-size: 13px; color: var(--muted); }
34
34
  /* Save & Apply is a group of its own: a gap from Cancel and Send Test
35
35
  (on a phone: one line, those two at the left, it at the right) */
36
- .btn-save { background: #2e7d32; color: #fff; font-size: 15px; min-height: 42px; padding: 10px 24px; margin-left: 40px; }
36
+ .btn-save { background: #2e7d32; color: #fff; margin-left: 40px; }
37
37
  @media (max-width: 600px) {
38
- .btn-save { margin-left: auto; padding: 10px 16px; white-space: nowrap; }
38
+ .btn-save { white-space: nowrap; }
39
+ .pr-actions .pr-save-wrap { margin-left: auto; }
40
+ .pr-actions { gap: 8px; padding: 12px 8px; }
39
41
  .pr-actions .btn { white-space: nowrap; }
40
42
  .pr-status { flex-basis: 100%; }
41
43
  }
42
44
  .btn-save:hover:not(:disabled) { background: #388e3c; }
43
- .pr-console { background: #111; color: #ddd; font-family: monospace; font-size: 12px; padding: 12px; border-radius: 6px; white-space: pre-wrap; max-height: 320px; overflow: auto; margin-bottom: 16px; display: none; scroll-margin-bottom: 90px; }
45
+ /* The note hangs under Save & Apply without moving it: the buttons
46
+ stay on one line, tops level */
47
+ .pr-save-wrap { position: relative; display: inline-flex; margin-left: 40px; }
48
+ .pr-save-wrap .btn-save { margin-left: 0; }
49
+ .pr-safe { display: none; position: absolute; top: 100%; right: 0; margin-top: 3px; font-size: 11px; color: var(--success); white-space: nowrap; }
50
+ .pr-safe.on { display: block; }
51
+ .pr-actions:has(.pr-safe.on) { padding-bottom: 28px; }
52
+ /* Save and Send Test progress: a popup like Firmware Config's */
53
+ .pr-run .pr-modal-box { max-width: 720px; border-radius: 12px; padding: 24px; max-height: 80vh; display: flex; flex-direction: column; }
54
+ .pr-run h3 { font-size: 18px; margin-bottom: 16px; }
55
+ .pr-run-msg { color: var(--text); margin-bottom: 16px; font-size: 14px; }
56
+ .pr-run-msg.ok { color: var(--success); }
57
+ .pr-run-msg.err { color: var(--error); }
58
+ .pr-console { background: #0d0d0d; color: #ddd; font-family: monospace; font-size: 12px; padding: 12px; border-radius: 6px; white-space: pre-wrap; word-wrap: break-word; height: 300px; max-height: 50vh; overflow-y: auto; margin-bottom: 16px; }
44
59
  .pr-console .err { color: var(--error); font-weight: 600; }
45
60
  .pr-console .ok { color: var(--success); }
61
+ .pr-run .btn { padding: 10px 20px; font-size: 14px; }
46
62
  .pr-error { color: var(--error); font-size: 13px; margin: 8px 0; font-weight: 500; scroll-margin-bottom: 90px; }
47
63
  .pr-modal { position: fixed; inset: 0; background: rgba(0,0,0,0.7); display: none; align-items: center; justify-content: center; z-index: 10; padding: 20px; }
48
64
  .pr-modal.open { display: flex; }
@@ -50,10 +66,9 @@
50
66
  .pr-modal-box h3 { color: #fff; margin-bottom: 12px; font-size: 16px; }
51
67
  .pr-modal-box p { white-space: pre-wrap; margin-bottom: 20px; font-size: 14px; line-height: 1.5; }
52
68
  .pr-modal-box .pr-buttons { display: flex; gap: 10px; justify-content: flex-end; }
53
- .pr-discard .pr-modal-box { border: 3px solid #d32f2f; }
54
- .pr-discard h3 { color: #ff5252; font-size: 24px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; }
55
- .pr-discard p { color: #ff8a80; font-size: 18px; font-weight: 700; }
56
- .pr-discard .btn { font-size: 15px; min-height: 42px; padding: 10px 18px; }
69
+ .pr-discard h3 { font-size: 18px; }
70
+ .pr-discard p { font-size: 15px; }
71
+ .pr-discard .btn { font-size: 14px; min-height: 38px; padding: 8px 16px; }
57
72
  .btn-keep { background: #2e7d32; color: #fff; }
58
73
  .btn-keep:hover { background: #388e3c; }
59
74
  .btn-discard { background: #c62828; color: #fff; }
@@ -87,7 +102,7 @@
87
102
  .nt-name { color: #fff; }
88
103
  .nt-icon { display: inline-block; width: 24px; }
89
104
  .nt-table select.nt-input.nt-layer { width: auto; padding: 4px 6px; display: inline-block; font-family: inherit; }
90
- .nt-sub { display: block; margin-top: 4px; font-size: 12px; color: #8a8f98; white-space: nowrap; }
105
+ .nt-sub { display: block; margin-top: 4px; padding-left: 26px; font-size: 12px; color: #8a8f98; white-space: normal; }
91
106
  .nt-sub select.nt-input.nt-layer { font-size: 12px; padding: 2px 4px; max-width: 140px; }
92
107
  .nt-sub input.nt-input.nt-deg { width: 56px; font-size: 12px; padding: 2px 4px; display: inline-block; }
93
108
  .nt-foot { font-size: 12px; color: #8a8f98; margin: 0 0 16px; }
@@ -98,6 +113,17 @@
98
113
  .nt-inline { display: flex; gap: 6px; }
99
114
  .nt-inline .btn { min-height: 0; padding: 0 12px; white-space: nowrap; }
100
115
  .nt-inline .btn.nt-active { border-color: var(--accent); color: var(--accent); }
116
+ /* Printer URL: Fill in lists this page's address and the printer's
117
+ network addresses; the list is as wide as the field and button */
118
+ .nt-fill-wrap { position: relative; }
119
+ .nt-fill-menu { display: none; position: absolute; left: 0; right: 0; top: calc(100% + 4px); z-index: 5; background: #1e1e1e; border: 1px solid #555; border-radius: 8px; overflow: hidden; box-shadow: 0 6px 20px rgba(0,0,0,0.5); }
120
+ .nt-fill-menu.open { display: block; }
121
+ .nt-fill-menu button { display: block; width: 100%; text-align: left; background: none; border: none; border-top: 1px solid #333; color: var(--text); font: inherit; font-size: 14px; padding: 12px; cursor: pointer; }
122
+ .nt-fill-menu button:first-child { border-top: none; }
123
+ .nt-fill-menu button:hover, .nt-fill-menu button:focus { background: #3a3a3a; outline: none; }
124
+ .nt-fill-menu code { font-family: monospace; }
125
+ .nt-fill-menu small { display: block; color: var(--muted); font-size: 12px; margin-top: 2px; }
126
+ .nt-fill-menu .nt-fill-clear { color: var(--muted); }
101
127
  .nt-field .nt-hint a { color: var(--accent); }
102
128
  .nt-disabled .nt-body { opacity: 0.55; }
103
129
  .nt-unit { align-items: center; }
@@ -350,10 +376,12 @@
350
376
  </div>
351
377
  <div class="nt-field" style="grid-column: 1 / -1">
352
378
  <label for="nt-printer-url">Printer URL for buttons (optional)</label>
353
- <div class="nt-inline">
354
- <input class="nt-input" id="nt-printer-url" placeholder="http://u1" autocomplete="off" spellcheck="false">
355
- <button type="button" class="btn btn-secondary" id="nt-use-local">Use local IP</button>
356
- <button type="button" class="btn btn-secondary" id="nt-use-tailscale">Use Tailscale</button>
379
+ <div class="nt-fill-wrap">
380
+ <div class="nt-inline">
381
+ <input class="nt-input" id="nt-printer-url" placeholder="http://u1.home" autocomplete="off" spellcheck="false">
382
+ <button type="button" class="btn btn-secondary" id="nt-fill" aria-haspopup="true" aria-expanded="false">Fill in ▾</button>
383
+ </div>
384
+ <div class="nt-fill-menu" id="nt-fill-menu" role="menu"></div>
357
385
  </div>
358
386
  <div class="nt-hint" id="nt-printer-url-hint"></div>
359
387
  <div class="nt-public" id="nt-local-warn" style="display:none">
@@ -400,19 +428,32 @@
400
428
  </div>
401
429
  </div>
402
430
 
403
- <div class="pr-console" id="pr-console"></div>
404
431
  <div class="pr-error" id="pr-error" style="display:none"></div>
405
432
  <div class="pr-actions">
406
433
  <button type="button" class="btn btn-secondary" id="pr-close">Cancel</button>
407
434
  <button type="button" class="btn btn-secondary" id="pr-test">Send Test</button>
408
- <button type="button" class="btn btn-save" id="pr-save">Save &amp; Apply</button>
435
+ <span class="pr-save-wrap">
436
+ <button type="button" class="btn btn-save" id="pr-save">Save &amp; Apply</button>
437
+ <span class="pr-safe" id="pr-safe">✓ Safe to save while printing</span>
438
+ </span>
409
439
  <span class="pr-status" id="pr-status"></span>
410
440
  </div>
411
441
 
442
+ <div class="pr-modal pr-run" id="pr-run" role="dialog" aria-labelledby="pr-run-title">
443
+ <div class="pr-modal-box">
444
+ <h3 id="pr-run-title"></h3>
445
+ <div class="pr-run-msg" id="pr-run-msg"></div>
446
+ <div class="pr-console" id="pr-console"></div>
447
+ <div class="pr-buttons">
448
+ <button type="button" class="btn btn-secondary" id="pr-run-close" disabled>Close</button>
449
+ </div>
450
+ </div>
451
+ </div>
452
+
412
453
  <div class="pr-modal pr-discard" id="pr-discard" role="alertdialog" aria-labelledby="pr-discard-title">
413
454
  <div class="pr-modal-box">
414
- <h3 id="pr-discard-title">⚠ Warning: your changes will be lost</h3>
415
- <p>You are leaving without saving. The changes you made on this page will NOT be kept.</p>
455
+ <h3 id="pr-discard-title">Leave without saving?</h3>
456
+ <p>The changes you made on this page will not be kept.</p>
416
457
  <div class="pr-buttons">
417
458
  <button type="button" class="btn btn-discard" id="pr-discard-yes" disabled>Discard changes</button>
418
459
  <button type="button" class="btn btn-keep" id="pr-discard-no">Keep editing</button>
@@ -441,7 +482,6 @@
441
482
  const el = id => document.getElementById(id);
442
483
  const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
443
484
  let state = null;
444
- let localWarned = false; // the local IP popup shows once per opening
445
485
  let saved = ''; // the payload as last loaded or saved
446
486
 
447
487
  // ---- Moonraker ------------------------------------------------------
@@ -539,6 +579,8 @@
539
579
  : '';
540
580
  const calib = meta.id === 'calibration'
541
581
  ? '<span class="nt-sub">Notifies when complete, failed or requires user intervention</span>'
582
+ : meta.id === 'started' && state.meta.preprint
583
+ ? `<span class="nt-sub"><label><input type="checkbox" id="nt-preprint"${state.preprint_done ? ' checked' : ''}> Notify when pre-print calibrations finish</label></span>`
542
584
  : meta.id === 'filament_change'
543
585
  ? `<span class="nt-sub"><label style="margin-right:12px"><input type="checkbox" id="nt-fc-loaded"${state.filament_change_events.includes('loaded') ? ' checked' : ''}> Loaded</label><label><input type="checkbox" id="nt-fc-unloaded"${state.filament_change_events.includes('unloaded') ? ' checked' : ''}> Unloaded</label></span>`
544
586
  : meta.id === 'chamber_waiting'
@@ -648,9 +690,9 @@
648
690
  'notifications, including camera images, model previews and file names.\n\n' +
649
691
  'It is fine for testing. For everyday use, setting up your own ntfy server is a good idea. ' +
650
692
  'On the public server, use a long random topic (the Random button creates one).';
651
- const LOCAL_WARNING = 'With the local IP, the Web UI and Live Camera buttons only work when your phone ' +
652
- 'is on the same network as the printer.\n\nUse Tailscale (or another address your phone can reach) ' +
653
- 'for buttons that work from anywhere.';
693
+ const TG_WARNING = 'Telegram does not support clickable URLs without a <code>.</code> (period character), ' +
694
+ 'so the Web UI and Live Camera buttons won\'t work in Telegram. Pick an IP address from <b>Fill in</b>, ' +
695
+ 'or use a full name such as <code>u1.home</code>.';
654
696
  const isPublic = server => /^https?:\/\/(www\.)?ntfy\.sh\/?$/i.test(server.trim());
655
697
 
656
698
  function randomTopic() {
@@ -676,23 +718,74 @@
676
718
  try { return new URL(url).hostname.toLowerCase(); } catch (e) { return ''; }
677
719
  }
678
720
 
721
+ // The warnings follow the field once it's left (or filled in), not
722
+ // while typing
679
723
  function updatePrinterUrl() {
680
724
  const url = el('nt-printer-url').value.trim();
681
725
  el('nt-local-warn').style.display = url && isLanOnly(url) ? '' : 'none';
682
- const same = (host) => !!host && url.replace(/\/+$/, '').toLowerCase() === ('http://' + host).toLowerCase();
683
- el('nt-use-local').classList.toggle('nt-active', same(state.meta.local_ip));
684
- el('nt-use-tailscale').classList.toggle('nt-active', same(state.meta.tailscale_host));
685
726
  const prov = el('nt-provider').value;
686
727
  el('nt-printer-url-hint').innerHTML = prov === 'pushover'
687
728
  ? 'Adds a <b>Web UI</b> link. Without it, fault notifications link to the Error Index.'
688
729
  : ['gotify', 'telegram', 'discord', 'discord_dm'].includes(prov)
689
730
  ? 'Adds <b>Web UI</b> and <b>Live Camera</b> links. Leave empty for no links.'
690
731
  : 'Adds <b>Web UI</b> and <b>Live Camera</b> buttons. Leave empty for no buttons.';
691
- const tg = prov === 'telegram' && state.meta.tailscale_ip && hostOf(url) === (state.meta.tailscale_host || '').toLowerCase();
732
+ const host = hostOf(url);
733
+ const tg = prov === 'telegram' && el('nt-push-enabled').checked && !!host && !host.includes('.') && !host.includes(':');
692
734
  el('nt-tg-warn').style.display = tg ? '' : 'none';
693
- if (tg) el('nt-tg-warn').textContent = `Telegram can't link to a Tailscale name, so the Tailscale IP (${state.meta.tailscale_ip}) is used for Telegram links.`;
735
+ if (tg) el('nt-tg-warn').innerHTML = TG_WARNING;
694
736
  }
695
737
 
738
+ // Fill in: this page's own address (how you reach the printer now),
739
+ // and the IPv4 address of each network interface Moonraker reports
740
+ // (/machine/system_info), by interface name; nothing is detected by
741
+ // name. Then Clear.
742
+ let fillChoices = null;
743
+ async function fillOptions() {
744
+ if (fillChoices) return fillChoices;
745
+ const out = [];
746
+ if (/^https?:$/.test(location.protocol) && location.hostname) {
747
+ out.push({ url: location.protocol + '//' + location.host, html:
748
+ `This browser's address: <code>${esc(location.host)}</code><small>Works wherever this address works for you</small>` });
749
+ }
750
+ try {
751
+ const info = await api('/machine/system_info');
752
+ const net = (info && info.system_info && info.system_info.network) || {};
753
+ for (const [name, iface] of Object.entries(net)) {
754
+ if (name === 'lo') continue;
755
+ for (const a of iface.ip_addresses || []) {
756
+ if (a.family !== 'ipv4' || a.is_link_local || !a.address || a.address.startsWith('127.')) continue;
757
+ out.push({ url: 'http://' + a.address, html: `${esc(name)}: <code>${esc(a.address)}</code>` });
758
+ }
759
+ }
760
+ } catch (e) { /* the browser's address is still offered */ }
761
+ fillChoices = out;
762
+ return out;
763
+ }
764
+ function closeFill() {
765
+ el('nt-fill-menu').classList.remove('open');
766
+ el('nt-fill').setAttribute('aria-expanded', 'false');
767
+ }
768
+ async function openFill() {
769
+ const menu = el('nt-fill-menu');
770
+ const choices = await fillOptions();
771
+ menu.innerHTML = choices.map((c, i) =>
772
+ `<button type="button" role="menuitem" data-i="${i}">${c.html}</button>`).join('') +
773
+ '<button type="button" role="menuitem" class="nt-fill-clear" data-i="clear">Clear (no buttons)</button>';
774
+ menu.querySelectorAll('button').forEach(b => b.onclick = () => {
775
+ el('nt-printer-url').value = b.dataset.i === 'clear' ? '' : choices[+b.dataset.i].url;
776
+ closeFill();
777
+ updatePrinterUrl();
778
+ });
779
+ menu.classList.add('open');
780
+ el('nt-fill').setAttribute('aria-expanded', 'true');
781
+ const first = menu.querySelector('button');
782
+ if (first) first.focus();
783
+ }
784
+ document.addEventListener('click', e => {
785
+ if (!e.target.closest('.nt-fill-wrap')) closeFill();
786
+ });
787
+ document.addEventListener('keydown', e => { if (e.key === 'Escape') closeFill(); });
788
+
696
789
  function updatePublicWarning() {
697
790
  const pub = el('nt-provider').value === 'ntfy' && isPublic(el('nt-server').value);
698
791
  el('nt-public-warn').style.display = pub ? '' : 'none';
@@ -766,7 +859,6 @@
766
859
  // ---- load / collect ----------------------------------------------------
767
860
  function render(data) {
768
861
  state = data;
769
- localWarned = false;
770
862
  el('pr-version').textContent = data.meta.version ? `pushraker ${data.meta.version}` : '';
771
863
  el('nt-enabled').checked = data.enabled;
772
864
  el('nt-push-enabled').checked = data.push_enabled !== false;
@@ -841,28 +933,17 @@
841
933
  el('nt-auth').onchange = updateAuth;
842
934
  el('nt-provider').onchange = updateProvider;
843
935
  el('nt-use-public').onclick = usePublicServer;
844
- el('nt-printer-url').oninput = updatePrinterUrl;
845
- el('nt-use-local').disabled = !data.meta.local_ip;
846
- el('nt-use-local').onclick = async () => {
847
- if (!localWarned && !await confirmModal('Use the local IP?', LOCAL_WARNING, 'Use local IP')) return;
848
- localWarned = true;
849
- el('nt-printer-url').value = 'http://' + data.meta.local_ip;
850
- updatePrinterUrl();
936
+ el('nt-printer-url').onchange = updatePrinterUrl;
937
+ el('nt-fill').onclick = e => {
938
+ e.stopPropagation();
939
+ if (el('nt-fill-menu').classList.contains('open')) closeFill(); else openFill();
851
940
  };
852
- const ts = data.meta.tailscale_host;
853
- // First setup only: suggest the best printer address. Once saved,
854
- // an empty field means "no buttons" and is left alone.
941
+ // First setup only: the address this page was opened with. Once
942
+ // saved, an empty field means "no buttons" and is left alone.
855
943
  const firstSetup = !data.enabled && !data.server && !data.pushover_user && !data.has_secret;
856
- if (firstSetup && !data.printer_url) {
857
- if (ts) el('nt-printer-url').value = 'http://' + ts;
858
- else if (data.meta.local_ip) el('nt-printer-url').value = 'http://' + data.meta.local_ip;
944
+ if (firstSetup && !data.printer_url && /^https?:$/.test(location.protocol) && location.hostname) {
945
+ el('nt-printer-url').value = location.protocol + '//' + location.host;
859
946
  }
860
- el('nt-use-tailscale').disabled = !ts;
861
- el('nt-use-tailscale').title = ts ? `http://${ts}` : 'Tailscale is not running on the printer';
862
- el('nt-use-tailscale').onclick = () => {
863
- el('nt-printer-url').value = 'http://' + ts;
864
- updatePrinterUrl();
865
- };
866
947
  updatePrinterUrl();
867
948
  el('nt-server').oninput = updatePublicWarning;
868
949
  el('nt-topic').oninput = () => {
@@ -885,6 +966,8 @@
885
966
  };
886
967
  });
887
968
  el('pr-status').textContent = data.meta.summary || '';
969
+ // During a print job: every setting applies live, nothing restarts
970
+ el('pr-safe').classList.toggle('on', !!data.meta.busy);
888
971
  el('pr-loading').classList.add('pr-hidden');
889
972
  el('nt-root').classList.remove('pr-hidden');
890
973
  saved = JSON.stringify(collect(false));
@@ -968,6 +1051,7 @@
968
1051
  filament_low_percent: parseInt(el('nt-fl-percent').value, 10) || 0,
969
1052
  filament_low_grams: parseInt(el('nt-fl-grams').value, 10) || 0,
970
1053
  filament_unknown: el('nt-fl-unknown').checked,
1054
+ preprint_done: el('nt-preprint') ? el('nt-preprint').checked : !!state.preprint_done,
971
1055
  email_enabled: emailEnabled,
972
1056
  email_host: el('nt-email-host').value.trim(),
973
1057
  email_port: parseInt(el('nt-email-port').value, 10) || 0,
@@ -993,17 +1077,33 @@
993
1077
  if (msg) el('pr-error').scrollIntoView({ block: 'nearest', behavior: 'smooth' });
994
1078
  }
995
1079
 
996
- function showConsole(lines, ok) {
1080
+ // Save and Send Test run in a popup (as Firmware Config's actions
1081
+ // do): a message, the log, and Close once it's finished
1082
+ function runStart(title, message) {
1083
+ el('pr-run-title').textContent = title;
1084
+ runMessage(message, '');
1085
+ el('pr-console').innerHTML = '';
1086
+ el('pr-run-close').disabled = true;
1087
+ el('pr-run').classList.add('open');
1088
+ }
1089
+ function runMessage(html, kind) {
1090
+ el('pr-run-msg').innerHTML = html;
1091
+ el('pr-run-msg').className = 'pr-run-msg' + (kind ? ' ' + kind : '');
1092
+ }
1093
+ function runEnd(html, ok) {
1094
+ runMessage(html, ok ? 'ok' : 'err');
1095
+ el('pr-run-close').disabled = false;
1096
+ el('pr-run-close').focus();
1097
+ }
1098
+ el('pr-run-close').onclick = () => el('pr-run').classList.remove('open');
1099
+
1100
+ function showConsole(lines) {
997
1101
  const box = el('pr-console');
998
1102
  box.innerHTML = lines.map(l => {
999
1103
  const c = l.startsWith('!! ') ? 'err' : (/^(Sent to|Test notification sent|Settings saved)/.test(l) ? 'ok' : '');
1000
1104
  return `<div class="${c}">${esc(l.replace(/^!! /, ''))}</div>`;
1001
1105
  }).join('');
1002
- box.style.display = lines.length ? 'block' : 'none';
1003
1106
  box.scrollTop = box.scrollHeight;
1004
- // The console is at the end of the page: bring it into view, or
1005
- // on a long page it is never seen
1006
- if (lines.length) box.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
1007
1107
  }
1008
1108
 
1009
1109
  function busy(on, what) {
@@ -1017,15 +1117,18 @@
1017
1117
  let payload;
1018
1118
  try { payload = collect(true); } catch (e) { showError(e.message); return; }
1019
1119
  busy(true, 'Saving…');
1120
+ runStart('Save & Apply', 'Saving and applying settings…');
1020
1121
  try {
1021
1122
  const data = await api('/server/pushraker/config', 'POST', payload);
1022
1123
  const notes = (data.notes || []).slice();
1023
1124
  render(data);
1024
- showConsole(['Settings saved and applied. Nothing restarts: they are in effect now, during a print job too.'].concat(notes), true);
1125
+ showConsole(['Settings saved and applied. Nothing restarts: they are in effect now, during a print job too.'].concat(notes));
1025
1126
  el('pr-status').textContent = 'Saved and applied';
1127
+ runEnd('Done', true);
1026
1128
  } catch (e) {
1027
- showError(e.message);
1129
+ showConsole(['!! ' + e.message]);
1028
1130
  el('pr-status').textContent = '';
1131
+ runEnd('Not saved', false);
1029
1132
  } finally {
1030
1133
  busy(false);
1031
1134
  }
@@ -1036,15 +1139,18 @@
1036
1139
  let payload;
1037
1140
  try { payload = collect(true); } catch (e) { showError(e.message); return; }
1038
1141
  busy(true, 'Sending a test notification…');
1039
- showConsole(['Sending a test notification (this can take up to a minute per destination)…']);
1142
+ runStart('Send Test', 'Sending a test notification (this can take up to a minute per destination)…');
1143
+ const failed = 'Test failed.' + guideLink('troubleshooting', 'Troubleshooting');
1040
1144
  try {
1041
1145
  const data = await api('/server/pushraker/test', 'POST', payload);
1042
- showConsole(data.lines || [], data.ok);
1146
+ showConsole(data.lines || []);
1043
1147
  if (data.ok) el('pr-status').textContent = 'Test sent';
1044
- else el('pr-status').innerHTML = 'Test failed.' + guideLink('troubleshooting', 'Troubleshooting');
1148
+ else el('pr-status').innerHTML = failed;
1149
+ runEnd(data.ok ? 'Test sent' : failed, data.ok);
1045
1150
  } catch (e) {
1046
- showConsole(['!! ' + e.message], false);
1047
- el('pr-status').innerHTML = 'Test failed.' + guideLink('troubleshooting', 'Troubleshooting');
1151
+ showConsole(['!! ' + e.message]);
1152
+ el('pr-status').innerHTML = failed;
1153
+ runEnd(failed, false);
1048
1154
  } finally {
1049
1155
  busy(false);
1050
1156
  }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pushraker
3
- Version: 0.2.2
3
+ Version: 0.2.5
4
4
  Summary: Push notifications for Klipper printers: a Moonraker component with pictures, sent through Apprise (ntfy, Pushover, Telegram, Discord, webhooks, email)
5
5
  Author: noon92
6
6
  License-Expression: GPL-3.0-or-later
@@ -1183,7 +1183,7 @@ async def test_file_pauses():
1183
1183
  (55, "", "filament change")],
1184
1184
  c._job_pauses)
1185
1185
  check("started says so", log and log[0]["body"].endswith(
1186
- "\n\nPrint job contains 3 pauses (layers 12, 40 and 55)."),
1186
+ "\n\n⏸️ Print job contains 3 pauses (layers 12, 40 and 55)."),
1187
1187
  log and log[0]["body"])
1188
1188
  log.clear()
1189
1189
  # The file's pause: file position just past the pause line
@@ -2243,6 +2243,80 @@ async def test_config_lines():
2243
2243
  SECRETS.clear()
2244
2244
 
2245
2245
 
2246
+ async def test_preprint():
2247
+ print("Pre-print calibrations: listed at the start, then complete")
2248
+ reset_world()
2249
+ log = []
2250
+ ntfy = FakeService(log, "ntfy")
2251
+ server, c = make({}, {"started": [("ntfy", ntfy, False)],
2252
+ "preprint_done": [("ntfy", ntfy, False)]})
2253
+ STATE["print_task_config"] = dict(
2254
+ auto_bed_leveling=True, flow_calibrate=True, shaper_calibrate=False,
2255
+ flow_calib_extruders=[True] * 4,
2256
+ extruders_used=[False, False, False, True])
2257
+
2258
+ async def msm(action):
2259
+ await c._on_status_update(
2260
+ {"machine_state_manager": {"main_state": 1,
2261
+ "action_code": action}}, 0)
2262
+ await start_job(server)
2263
+ await asyncio.sleep(0.3)
2264
+ check("Print started lists the chosen calibrations",
2265
+ len(log) == 1 and "Pre-print calibrations selected: Bed levelling, "
2266
+ "Extrusion flow calibration (pressure advance)." in log[0]["body"],
2267
+ [e["body"] for e in log])
2268
+ log.clear()
2269
+ for a in (136, 0, 2, 0, 257, 258, 256, 0): # as logged on a U1
2270
+ await msm(a)
2271
+ await asyncio.sleep(0.3)
2272
+ check("not complete while a chosen one (T4's flow) is still to run",
2273
+ log == [], [e["title"] for e in log])
2274
+ await msm(323)
2275
+ await msm(0)
2276
+ await asyncio.sleep(0.3)
2277
+ check("complete once the last one is back to idle",
2278
+ [e["title"] for e in log] ==
2279
+ ["▶️ U1 pre-print calibrations complete"]
2280
+ and "Bed levelling and Extrusion flow calibration (pressure advance) done"
2281
+ in log[0]["body"], [(e["title"], e["body"]) for e in log])
2282
+ log.clear()
2283
+ await c._on_status_update({"print_stats": {"info": {"current_layer": 1}}}, 0)
2284
+ await asyncio.sleep(0.2)
2285
+ check("sent once", log == [], [e["title"] for e in log])
2286
+ # A chosen flow calibration that doesn't run (that toolhead already
2287
+ # calibrated): layer 1 ends the wait
2288
+ STATE["print_task_config"].update(auto_bed_leveling=False)
2289
+ STATE["print_stats"] = ps("complete")
2290
+ await server.handlers["job_state:state_changed"](
2291
+ JobEvent.COMPLETE, {}, STATE["print_stats"])
2292
+ await asyncio.sleep(0.2)
2293
+ log.clear()
2294
+ await start_job(server)
2295
+ await asyncio.sleep(0.2)
2296
+ log.clear()
2297
+ STATE["print_stats"]["info"] = {"current_layer": 1}
2298
+ await c._on_status_update({"print_stats": {"info": {"current_layer": 1}}}, 0)
2299
+ await asyncio.sleep(0.3)
2300
+ check("a skipped one: complete when layer 1 begins",
2301
+ [e["title"] for e in log] == ["▶️ U1 pre-print calibrations complete"],
2302
+ [e["title"] for e in log])
2303
+ log.clear()
2304
+ # None chosen: no line, no notification
2305
+ STATE["print_task_config"].update(flow_calibrate=False)
2306
+ STATE["print_stats"] = ps("complete")
2307
+ await server.handlers["job_state:state_changed"](
2308
+ JobEvent.COMPLETE, {}, STATE["print_stats"])
2309
+ await asyncio.sleep(0.2)
2310
+ log.clear()
2311
+ await start_job(server)
2312
+ await asyncio.sleep(0.3)
2313
+ await c._on_status_update({"print_stats": {"info": {"current_layer": 1}}}, 0)
2314
+ await asyncio.sleep(0.2)
2315
+ check("none chosen: no line and no notification",
2316
+ len(log) == 1 and "Pre-print" not in log[0]["body"],
2317
+ [(e["title"], e["body"]) for e in log])
2318
+
2319
+
2246
2320
  async def test_old_names():
2247
2321
  """0.1's names keep working: the remote method, the low-spool memory."""
2248
2322
  data = os.path.join(WORK, "data")
@@ -2267,7 +2341,7 @@ async def run_component_tests():
2267
2341
  test_faults_over_a_job, test_spool_switch, test_ace, test_file_pauses, test_file_mode, test_generic_printer, test_status_report, test_time_left, test_calibration, test_gotify, test_image_names, test_fault_emoji, test_send_gap, test_macro_notify, test_queue_line, test_chamber, test_filament_change, test_backup_order, test_console,
2268
2342
  test_driver_hot,
2269
2343
  test_print_by_object,
2270
- test_no_secrets_in_logs, test_config_lines, test_old_names):
2344
+ test_no_secrets_in_logs, test_config_lines, test_old_names, test_preprint):
2271
2345
  try:
2272
2346
  await t()
2273
2347
  except Exception as e: # report and carry on
@@ -74,33 +74,18 @@ def run_settings_tests():
74
74
  gopts["error"].startswith("none, gotifys://g.example.com:8443/")
75
75
  and gopts["web_ui_url"] == "http://u1/"
76
76
  and gopts["camera_url"] == "http://u1/webcam/webrtc", gopts)
77
- bad(dict(provider="telegram", secret="12345:" + "A" * 35,
78
- telegram_chat="123", printer_url="http://u1"),
79
- "rejects a dot-less printer host for Telegram (links are dropped)")
80
77
  st.validate(dict(provider="telegram", secret="12345:" + "A" * 35,
81
78
  telegram_chat="123", printer_url="http://100.64.0.10"),
82
79
  fresh(), ENV)
83
80
  st.validate(dict(provider="ntfy", server="https://ntfy.example.com",
84
81
  topic="u1", printer_url="http://u1"), fresh(), ENV)
85
82
  check("a dot-less printer host is fine for the other services", True)
86
- ts = st.Env(cameras=ENV.cameras, tailscale=("u1", "100.64.0.10"))
87
83
  tg = dict(enabled=True, provider="telegram", secret="12345:" + "A" * 35,
88
- telegram_chat="123", printer_url="http://U1/", camera="case")
89
- s = st.validate(tg, fresh(), ts)
90
- check("Telegram: the Tailscale name is accepted and sent as the IP",
91
- st.links(s, "test", ts)[:2] == [
92
- ("Web UI", "http://100.64.0.10/"),
93
- ("Live Camera", "http://100.64.0.10/webcam/webrtc")]
94
- and st.render_options(s, ts)["web_ui_url"] == "http://100.64.0.10/"
95
- and s["printer_url"] == "http://U1/", st.links(s, "test", ts))
96
- bad(dict(provider="telegram", secret="12345:" + "A" * 35,
97
- telegram_chat="123", printer_url="http://other"),
98
- "Telegram: another dot-less name is still refused", ts)
99
- s = st.validate(dict(enabled=True, provider="ntfy",
100
- server="https://ntfy.example.com", topic="u1",
101
- printer_url="http://u1"), fresh(), ts)
102
- check("other services keep the Tailscale name",
103
- st.links(s, "test", ts)[0] == ("Web UI", "http://u1/"))
84
+ telegram_chat="123", printer_url="http://u1/", camera="case")
85
+ s = st.validate(tg, fresh(), ENV)
86
+ check("Telegram: a dot-less printer URL is saved as entered (the page "
87
+ "warns)", st.links(s, "test", ENV)[0] == ("Web UI", "http://u1/"),
88
+ st.links(s, "test", ENV))
104
89
  bad(dict(provider="discord", secret="https://example.com/x"),
105
90
  "rejects a URL that isn't a Discord webhook")
106
91
 
@@ -111,6 +96,14 @@ def run_settings_tests():
111
96
  check("options list the enabled notifications",
112
97
  opts["started"].startswith("render, ntfys://ntfy.example.com/u1"),
113
98
  opts.get("started"))
99
+ pp = st.Env(cameras=ENV.cameras, preprint=True)
100
+ check("pre-print calibrations complete: Print started's destination, "
101
+ "on printers that have them, while its checkbox is on",
102
+ "preprint_done" not in opts
103
+ and st.render_options(s, pp).get("preprint_done", "").startswith(
104
+ "render, ntfys://ntfy.example.com/u1")
105
+ and "preprint_done" not in st.render_options(
106
+ dict(s, preprint_done=False), pp))
114
107
  comp = open(os.path.join(HERE, "..", "src", "pushraker",
115
108
  "component.py")).read()
116
109
  known = set(re.findall(r'(?:get|num)\(\s*"(\w+)"', comp))
File without changes
File without changes
File without changes