archive.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  1. import hashlib
  2. import html
  3. import json
  4. import logging
  5. import os
  6. import re
  7. import shutil
  8. import zipfile
  9. from datetime import date, datetime, time, timezone
  10. from pathlib import Path
  11. from defusedxml import ElementTree as ET
  12. from sqlalchemy import and_, or_, select, text
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from backend.app.core.config import settings
  15. from backend.app.core.tasks import spawn_background_task
  16. from backend.app.models.archive import PrintArchive
  17. from backend.app.models.filament import Filament
  18. from backend.app.models.printer import Printer
  19. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  20. from backend.app.utils.filename import clean_display_name
  21. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  22. logger = logging.getLogger(__name__)
  23. def _copy_and_fsync(src: Path, dst: Path, chunk_size: int = 1024 * 1024) -> None:
  24. """Copy src to dst with an explicit chunked read/write and fsync the dst.
  25. Replacement for shutil.copy2 in the archive pipeline. shutil.copy2 uses
  26. Linux sendfile(), which on some kernels/filesystems has returned a short
  27. count on the first call and truncated the destination for larger 3MF
  28. uploads (#1032, observed on Raspberry Pi OS bookworm / armv7l). An
  29. explicit loop with fsync avoids that path and guarantees the dest bytes
  30. are on disk before the caller inspects them as a ZIP.
  31. """
  32. with src.open("rb") as rf, dst.open("wb") as wf:
  33. while True:
  34. buf = rf.read(chunk_size)
  35. if not buf:
  36. break
  37. wf.write(buf)
  38. wf.flush()
  39. os.fsync(wf.fileno())
  40. shutil.copystat(src, dst)
  41. def resolve_display_stem(filename: str) -> str:
  42. """Return a clean human-readable stem from a 3MF/gcode filename.
  43. Bambu Studio's "Send to printer" dialog typically writes files like
  44. ``Plate_1.gcode.3mf`` (a sliced gcode payload wrapped in a 3MF container).
  45. The naive ``Path(filename).stem`` only drops the last suffix, leaving
  46. ``Plate_1.gcode`` — which then surfaces in the archive UI as a confusing
  47. ``Plate_1.gcode`` rather than ``Plate_1`` (#1152 follow-up).
  48. Strip the recognised print-format suffixes in order:
  49. - ``.gcode.3mf`` → bare stem (Bambu Studio FTP send)
  50. - ``.3mf`` → bare stem
  51. - ``.gcode`` → bare stem (rare standalone gcode upload)
  52. Anything else passes through unchanged.
  53. """
  54. name = Path(filename).name # drop any path components
  55. lower = name.lower()
  56. for suffix in (".gcode.3mf", ".3mf", ".gcode"):
  57. if lower.endswith(suffix):
  58. return name[: -len(suffix)]
  59. return Path(name).stem
  60. def _read_plate_index(plate) -> int | None:
  61. """Return the 1-based index of a ``slice_info.config`` ``<plate>`` element, or None.
  62. Bambu Studio and OrcaSlicer record it as a ``<metadata key="index"
  63. value="N"/>`` child — there is no ``plate_idx`` attribute on ``<plate>``
  64. itself, so an XPath predicate on one never matches (#2522).
  65. """
  66. for meta in plate.findall("metadata"):
  67. if meta.get("key") == "index":
  68. value = meta.get("value")
  69. if not value:
  70. return None
  71. try:
  72. return int(value)
  73. except ValueError:
  74. return None
  75. return None
  76. def peek_plate_index_in_3mf(file_path: Path) -> int | None:
  77. """Return the plate index a single-plate Bambu 3MF represents, or None.
  78. Reads only ``Metadata/slice_info.config`` to keep this cheap — used by
  79. the print-start callback to verify that the 3MF we just downloaded over
  80. FTP actually matches the plate the printer is running (#1204). The full
  81. ThreeMFParser does much more work and runs later inside ArchiveService.
  82. An all-plates export carries every plate, so "which plate is this file"
  83. has no answer; returning None there keeps the #1204 guard from reading
  84. plate 1 out of such a file, declaring a mismatch against the plate that
  85. is really running, and discarding a perfectly good 3MF (#2522).
  86. """
  87. try:
  88. with zipfile.ZipFile(file_path, "r") as zf:
  89. if "Metadata/slice_info.config" not in zf.namelist():
  90. return None
  91. content = zf.read("Metadata/slice_info.config").decode()
  92. root = ET.fromstring(content)
  93. plates = root.findall(".//plate")
  94. if len(plates) != 1:
  95. return None
  96. return _read_plate_index(plates[0])
  97. except Exception:
  98. return None
  99. _PLATE_SUFFIX_RE = re.compile(r"^(.*?)(\s*-\s*Plate\s+|_plate_)(\d+)$", re.IGNORECASE)
  100. def swap_plate_suffix(name: str | None, target_plate: int) -> str | None:
  101. """Return ``name`` with its trailing plate number replaced, or None.
  102. Bambu Studio names multi-plate uploads ``"<Project> - Plate <N>"`` (and
  103. a lowercase ``"_plate_<N>"`` variant exists too — see
  104. test_print_start_expected_promotion). When MQTT subtask_name lags
  105. across consecutive plates of the same model (#1204) the suffix points
  106. at the previous plate; swapping it gives us the correct upload to
  107. re-fetch from FTP. Returns None if no recognised suffix is present.
  108. """
  109. if not name:
  110. return None
  111. m = _PLATE_SUFFIX_RE.match(name)
  112. if not m:
  113. return None
  114. base, separator, _ = m.groups()
  115. return f"{base}{separator}{target_plate}"
  116. class ThreeMFParser:
  117. """Parser for Bambu Lab 3MF files."""
  118. def __init__(self, file_path: Path, plate_number: int | None = None):
  119. self.file_path = file_path
  120. self.plate_number = plate_number # Which plate was printed (1, 2, 3, etc.)
  121. self.metadata: dict = {}
  122. def parse(self) -> dict:
  123. """Extract metadata from 3MF file."""
  124. try:
  125. with zipfile.ZipFile(self.file_path, "r") as zf:
  126. self._parse_slice_info(zf) # Now sets self.plate_number from slice_info
  127. self._parse_project_settings(zf)
  128. self._parse_gcode_header(zf)
  129. self._parse_3dmodel(zf)
  130. self._extract_thumbnail(zf) # Uses correct plate_number for thumbnail
  131. # Enhance print_name with plate info if this is a multi-plate export
  132. plate_index = self.metadata.get("_plate_index")
  133. if plate_index and plate_index > 1:
  134. # Append plate number to distinguish from other plates
  135. existing_name = self.metadata.get("print_name", "")
  136. if existing_name and f"Plate {plate_index}" not in existing_name:
  137. self.metadata["print_name"] = f"{existing_name} - Plate {plate_index}"
  138. # ALWAYS prefer slice_info values - they contain ONLY filaments actually used in print
  139. # project_settings contains ALL configured filaments (AMS slots), not just used ones
  140. if self.metadata.get("_slice_filament_type"):
  141. self.metadata["filament_type"] = self.metadata["_slice_filament_type"]
  142. if self.metadata.get("_slice_filament_color"):
  143. self.metadata["filament_color"] = self.metadata["_slice_filament_color"]
  144. # Clean up internal keys
  145. self.metadata.pop("_slice_filament_type", None)
  146. self.metadata.pop("_slice_filament_color", None)
  147. self.metadata.pop("_plate_index", None)
  148. except Exception as e:
  149. # Return whatever metadata was extracted before the error, but
  150. # surface the failure so corrupted / truncated 3MF archives are
  151. # visible in support bundles (#1032).
  152. logger.warning(
  153. "ThreeMFParser: failed to parse %s: %s(%s) — returning partial metadata",
  154. self.file_path,
  155. type(e).__name__,
  156. e,
  157. )
  158. return self.metadata
  159. def _parse_slice_info(self, zf: zipfile.ZipFile):
  160. """Parse slice_info.config for print settings and printable objects."""
  161. try:
  162. if "Metadata/slice_info.config" in zf.namelist():
  163. content = zf.read("Metadata/slice_info.config").decode()
  164. root = ET.fromstring(content)
  165. # Extract printer_model_id from plate metadata
  166. # Format: <plate><metadata key="printer_model_id" value="C11" /></plate>
  167. for meta in root.findall(".//metadata"):
  168. key = meta.get("key")
  169. value = meta.get("value")
  170. if key == "printer_model_id" and value:
  171. from backend.app.utils.printer_models import normalize_printer_model_id
  172. normalized = normalize_printer_model_id(value)
  173. if normalized:
  174. self.metadata["sliced_for_model"] = normalized
  175. break
  176. # Loop every <plate> so multi-plate exports get summed file-level
  177. # totals. Pre-fix, this used `root.find(".//plate")` which
  178. # returned only the first plate — file-level `print_time_seconds`
  179. # / `filament_used_grams` reflected plate 1 alone, and the
  180. # archive card / project rollup under-reported by the number
  181. # of plates (#1593). Per-plate breakdown is still served by
  182. # the dedicated `/plates` endpoint.
  183. plates = root.findall(".//plate")
  184. summed_time = 0
  185. summed_grams = 0.0
  186. any_time_seen = False
  187. any_grams_seen = False
  188. for plate in plates:
  189. # Plate-level fields that only make sense at the file
  190. # level when there's exactly one plate. ``plate_number``
  191. # / ``_plate_index`` describe which plate the export
  192. # represents — meaningless for an all-plates 3MF, so we
  193. # only record them in the single-plate case. ``bed_type``
  194. # is also single-valued; we take the first plate's value
  195. # as a best-effort default for the archive metadata.
  196. plate_index_value: int | None = None
  197. for meta in plate.findall("metadata"):
  198. key = meta.get("key")
  199. value = meta.get("value")
  200. if key == "index" and value:
  201. try:
  202. plate_index_value = int(value)
  203. except ValueError:
  204. pass # Skip non-numeric plate index
  205. elif key == "prediction" and value:
  206. try:
  207. summed_time += int(value)
  208. any_time_seen = True
  209. except ValueError:
  210. pass
  211. elif key == "weight" and value:
  212. try:
  213. summed_grams += float(value)
  214. any_grams_seen = True
  215. except ValueError:
  216. pass
  217. elif key == "curr_bed_type" and value and "bed_type" not in self.metadata:
  218. self.metadata["bed_type"] = value
  219. # Per-plate object lists are only kept at the file level
  220. # when there's one plate — the skip-object affordance
  221. # operates on the plate being printed, which is the
  222. # `/plates` endpoint's job for multi-plate exports.
  223. if len(plates) == 1:
  224. if plate_index_value is not None:
  225. if not self.plate_number:
  226. self.plate_number = plate_index_value
  227. self.metadata["_plate_index"] = plate_index_value
  228. printable_objects: dict[int, str] = {}
  229. for obj in plate.findall("object"):
  230. identify_id = obj.get("identify_id")
  231. name = obj.get("name")
  232. skipped = obj.get("skipped", "false")
  233. if identify_id and name and skipped.lower() != "true":
  234. try:
  235. printable_objects[int(identify_id)] = name
  236. except ValueError:
  237. pass # Skip objects with non-numeric identify_id
  238. if printable_objects:
  239. self.metadata["printable_objects"] = printable_objects
  240. if any_time_seen:
  241. self.metadata["print_time_seconds"] = summed_time
  242. if any_grams_seen:
  243. self.metadata["filament_used_grams"] = round(summed_grams, 2)
  244. # Get filament info from filaments ACTUALLY USED in the print
  245. # slice_info has <filament id="1" type="PLA" color="#FFFFFF" used_g="100" />
  246. # Only include filaments where used_g > 0
  247. filaments = root.findall(".//filament")
  248. if filaments:
  249. # Collect unique filament types and colors for filaments that are actually used
  250. types = []
  251. colors = []
  252. for f in filaments:
  253. # Check if this filament is actually used in the print
  254. used_g = f.get("used_g", "0")
  255. try:
  256. used_amount = float(used_g)
  257. except (ValueError, TypeError):
  258. used_amount = 0
  259. # Only include if used_g > 0 (filament is actually consumed)
  260. if used_amount > 0:
  261. ftype = f.get("type")
  262. fcolor = f.get("color")
  263. if ftype and ftype not in types:
  264. types.append(ftype)
  265. if fcolor and fcolor not in colors:
  266. colors.append(fcolor)
  267. if types:
  268. self.metadata["_slice_filament_type"] = ", ".join(types)
  269. if colors:
  270. self.metadata["_slice_filament_color"] = ",".join(colors)
  271. # Collect per-slot filament usage for tracking & notifications
  272. filament_slots = []
  273. for f in filaments:
  274. slot_id = f.get("id")
  275. used_g_str = f.get("used_g", "0")
  276. try:
  277. used_g = float(used_g_str)
  278. except (ValueError, TypeError):
  279. used_g = 0
  280. if used_g > 0 and slot_id:
  281. filament_slots.append(
  282. {
  283. "slot_id": int(slot_id),
  284. "used_g": round(used_g, 2),
  285. "type": f.get("type", ""),
  286. "color": f.get("color", ""),
  287. }
  288. )
  289. if filament_slots:
  290. self.metadata["filament_slots"] = filament_slots
  291. except Exception:
  292. pass # Skip unparseable slice_info metadata
  293. def _parse_project_settings(self, zf: zipfile.ZipFile):
  294. """Parse project settings for print configuration."""
  295. try:
  296. if "Metadata/project_settings.config" in zf.namelist():
  297. content = zf.read("Metadata/project_settings.config").decode()
  298. try:
  299. data = json.loads(content)
  300. self._extract_filament_info(data)
  301. self._extract_print_settings(data)
  302. except json.JSONDecodeError:
  303. pass # Skip malformed project_settings JSON
  304. except Exception:
  305. pass # Skip unreadable project settings file
  306. def _parse_gcode_header(self, zf: zipfile.ZipFile):
  307. """Parse G-code file header for total layer count and printer model."""
  308. try:
  309. # Look for plate_1.gcode or similar
  310. gcode_files = [f for f in zf.namelist() if f.endswith(".gcode")]
  311. if not gcode_files:
  312. return
  313. # Read first 4KB of G-code (header contains metadata)
  314. gcode_path = gcode_files[0]
  315. with zf.open(gcode_path) as f:
  316. header = f.read(4096).decode("utf-8", errors="ignore")
  317. # Look for "; total layer number: XX" pattern
  318. match = re.search(r";\s*total\s+layer\s+number[:\s]+(\d+)", header, re.IGNORECASE)
  319. if match:
  320. self.metadata["total_layers"] = int(match.group(1))
  321. # Total filament usage. The slicer writes the print's totals into
  322. # the G-code header ("; total filament weight [g] : 126.26"). Only
  323. # a fallback — slice_info.config is more authoritative when present
  324. # — but it covers sliced outputs whose slice_info lacks per-filament
  325. # used_g, and it's the slicer's own figure regardless.
  326. if "filament_used_grams" not in self.metadata:
  327. match = re.search(r";\s*total\s+filament\s+weight\s*\[g\]\s*:\s*([\d.]+)", header, re.IGNORECASE)
  328. if match:
  329. self.metadata["filament_used_grams"] = float(match.group(1))
  330. if "filament_used_mm" not in self.metadata:
  331. match = re.search(r";\s*total\s+filament\s+length\s*\[mm\]\s*:\s*([\d.]+)", header, re.IGNORECASE)
  332. if match:
  333. self.metadata["filament_used_mm"] = float(match.group(1))
  334. # Look for printer_model in gcode header (fallback if not found in slice_info)
  335. # Format: "; printer_model = Bambu Lab X1 Carbon" or "; printer_model = X1C"
  336. if "sliced_for_model" not in self.metadata:
  337. match = re.search(r";\s*printer_model\s*=\s*(.+)", header, re.IGNORECASE)
  338. if match:
  339. from backend.app.utils.printer_models import normalize_printer_model
  340. raw_model = match.group(1).strip()
  341. self.metadata["sliced_for_model"] = normalize_printer_model(raw_model)
  342. except Exception:
  343. pass # G-code header parsing is best-effort; metadata may come from other sources
  344. def _extract_filament_info(self, data: dict):
  345. """Extract filament info from project settings — includes support
  346. materials so a PLA-model / PVA-support project shows both on the
  347. archive card badge (#1881).
  348. Earlier code filtered by ``filament_is_support``; that hid PVA
  349. (and any other soluble/breakaway support material) from the card
  350. even when the user had explicitly configured it, and made source
  351. 3MFs look single-material until the print completed. slice_info
  352. (parsed separately) is still preferred when present — it lists
  353. only filaments the print actually consumes, this fallback only
  354. runs on unsliced source 3MFs.
  355. """
  356. try:
  357. filament_types = data.get("filament_type", [])
  358. filament_colors = data.get("filament_colour", [])
  359. if not filament_types:
  360. return
  361. unique_types: list[str] = []
  362. for ftype in filament_types:
  363. if ftype and ftype not in unique_types:
  364. unique_types.append(ftype)
  365. unique_colors: list[str] = []
  366. for color in filament_colors:
  367. if color and color not in unique_colors:
  368. unique_colors.append(color)
  369. if unique_types:
  370. self.metadata["filament_type"] = ", ".join(unique_types)
  371. if unique_colors:
  372. self.metadata["filament_color"] = ",".join(unique_colors)
  373. except Exception:
  374. pass # Filament info is optional; fall back to slice_info values
  375. def _extract_print_settings(self, data: dict):
  376. """Extract print settings from JSON config."""
  377. try:
  378. # Layer height - usually an array, get first value
  379. if "layer_height" in data:
  380. val = data["layer_height"]
  381. if isinstance(val, list) and val:
  382. self.metadata["layer_height"] = float(val[0])
  383. elif isinstance(val, (int, float, str)):
  384. self.metadata["layer_height"] = float(val)
  385. # Nozzle diameter
  386. if "nozzle_diameter" in data:
  387. val = data["nozzle_diameter"]
  388. if isinstance(val, list) and val:
  389. self.metadata["nozzle_diameter"] = float(val[0])
  390. elif isinstance(val, (int, float, str)):
  391. self.metadata["nozzle_diameter"] = float(val)
  392. # Bed temperature - first layer or regular
  393. for key in ["bed_temperature_initial_layer", "bed_temperature"]:
  394. if key in data:
  395. val = data[key]
  396. if isinstance(val, list) and val:
  397. self.metadata["bed_temperature"] = int(float(val[0]))
  398. elif isinstance(val, (int, float, str)):
  399. self.metadata["bed_temperature"] = int(float(val))
  400. break
  401. # Nozzle temperature
  402. for key in ["nozzle_temperature_initial_layer", "nozzle_temperature"]:
  403. if key in data:
  404. val = data[key]
  405. if isinstance(val, list) and val:
  406. self.metadata["nozzle_temperature"] = int(float(val[0]))
  407. elif isinstance(val, (int, float, str)):
  408. self.metadata["nozzle_temperature"] = int(float(val))
  409. break
  410. # Printer model (extract and normalize)
  411. if "printer_model" in data:
  412. from backend.app.utils.printer_models import normalize_printer_model
  413. self.metadata["sliced_for_model"] = normalize_printer_model(data["printer_model"])
  414. # Build plate type — only set from project_settings if slice_info didn't already
  415. # provide it (slice_info is more authoritative as it reflects the exported plate).
  416. if "bed_type" not in self.metadata and "curr_bed_type" in data:
  417. val = data["curr_bed_type"]
  418. if isinstance(val, str) and val.strip():
  419. self.metadata["bed_type"] = val.strip()
  420. except Exception:
  421. pass # Print settings are optional; missing values are left unset
  422. def _extract_settings_from_content(self, content: str):
  423. """Extract print settings from config content."""
  424. settings_map = {
  425. "layer_height": ("layer_height", float),
  426. "nozzle_diameter": ("nozzle_diameter", float),
  427. "bed_temperature": ("bed_temperature", int),
  428. "nozzle_temperature": ("nozzle_temperature", int),
  429. }
  430. for key, (search_key, converter) in settings_map.items():
  431. if key not in self.metadata:
  432. try:
  433. # Try JSON format
  434. if f'"{search_key}"' in content:
  435. start = content.find(f'"{search_key}"')
  436. value_start = content.find(":", start) + 1
  437. value_end = content.find(",", value_start)
  438. if value_end == -1:
  439. value_end = content.find("}", value_start)
  440. value = content[value_start:value_end].strip().strip('"')
  441. self.metadata[key] = converter(value)
  442. except (ValueError, TypeError):
  443. pass # Skip settings with unconvertible values
  444. def _parse_3dmodel(self, zf: zipfile.ZipFile):
  445. """Parse 3D/3dmodel.model for MakerWorld metadata."""
  446. try:
  447. model_path = "3D/3dmodel.model"
  448. if model_path not in zf.namelist():
  449. return
  450. content = zf.read(model_path).decode("utf-8", errors="ignore")
  451. # Parse XML metadata elements
  452. # MakerWorld adds metadata like: <metadata name="Designer">username</metadata>
  453. metadata_pattern = r'<metadata\s+name="([^"]+)"[^>]*>([^<]*)</metadata>'
  454. matches = re.findall(metadata_pattern, content)
  455. # 3MF metadata values are XML-encoded — `&` becomes `&amp;`, etc.
  456. # ProjectPageParser learned this the hard way: BambuStudio sometimes
  457. # writes triple-encoded payloads (`&amp;amp;amp;`), so we unescape
  458. # in a loop until the string stabilises. Without this, a Title like
  459. # "Foo & Bar" lands in the DB as raw "Foo &amp; Bar" and React then
  460. # double-escapes it on render to "Foo &amp;amp; Bar" (#1658).
  461. makerworld_fields = {}
  462. for name, value in matches:
  463. decoded = value.strip()
  464. prev = None
  465. while prev != decoded:
  466. prev = decoded
  467. decoded = html.unescape(decoded)
  468. makerworld_fields[name] = decoded
  469. # Check for direct MakerWorld URL in content
  470. url_pattern = r'https?://makerworld\.com/[^\s<>"\']+/models/(\d+)'
  471. url_match = re.search(url_pattern, content)
  472. if url_match:
  473. self.metadata["makerworld_url"] = url_match.group(0)
  474. self.metadata["makerworld_model_id"] = url_match.group(1)
  475. # Extract model ID from DSM reference in image URLs
  476. # Format: https://makerworld.bblmw.com/makerworld/model/DSM00000001275614/...
  477. # The numeric part (1275614) is the MakerWorld model ID
  478. if "makerworld_url" not in self.metadata:
  479. dsm_pattern = r"DSM0+(\d+)"
  480. dsm_match = re.search(dsm_pattern, content)
  481. if dsm_match:
  482. model_id = dsm_match.group(1)
  483. self.metadata["makerworld_url"] = f"https://makerworld.com/en/models/{model_id}"
  484. self.metadata["makerworld_model_id"] = model_id
  485. # Store designer info
  486. if "Designer" in makerworld_fields:
  487. self.metadata["designer"] = makerworld_fields["Designer"]
  488. if "Title" in makerworld_fields:
  489. self.metadata["print_name"] = makerworld_fields["Title"]
  490. except Exception:
  491. pass # MakerWorld/3dmodel metadata is optional
  492. def _extract_thumbnail(self, zf: zipfile.ZipFile):
  493. """Extract thumbnail image from 3MF.
  494. If a plate_number was specified, try to use that plate's thumbnail first.
  495. """
  496. thumbnail_paths = []
  497. # If a specific plate was printed, try that thumbnail first
  498. if self.plate_number:
  499. thumbnail_paths.append(f"Metadata/plate_{self.plate_number}.png")
  500. # Fallback to default paths
  501. thumbnail_paths.extend(
  502. [
  503. "Metadata/plate_1.png",
  504. "Metadata/thumbnail.png",
  505. "Metadata/model_thumbnail.png",
  506. # Project-wide thumbnail BambuStudio embeds at upload time. We
  507. # only reach this when BS hasn't written a per-plate
  508. # ``Metadata/plate_N.png`` — most notably the #1493 cross-class
  509. # re-slice path where ``--arrange`` rearranges objects but the
  510. # CLI then doesn't emit a fresh per-plate preview. The
  511. # ``_middle`` size is the editor-quality variant (~500 KB);
  512. # ``_small`` and ``_3mf`` are smaller alternates if it's not
  513. # present. Without this fallback the re-sliced archive cards
  514. # render without a cover image.
  515. "Auxiliaries/.thumbnails/thumbnail_middle.png",
  516. "Auxiliaries/.thumbnails/thumbnail_small.png",
  517. "Auxiliaries/.thumbnails/thumbnail_3mf.png",
  518. ]
  519. )
  520. for thumb_path in thumbnail_paths:
  521. if thumb_path in zf.namelist():
  522. self.metadata["_thumbnail_data"] = zf.read(thumb_path)
  523. self.metadata["_thumbnail_ext"] = ".png"
  524. break
  525. def extract_printable_objects_from_3mf(
  526. data: bytes, plate_number: int | None = None, include_positions: bool = False
  527. ) -> dict[int, str] | dict[int, dict] | tuple[dict[int, dict], list | None]:
  528. """Extract printable objects from 3MF file bytes.
  529. This is a lightweight function used during print start to get the list
  530. of objects that can be skipped.
  531. Args:
  532. data: Raw bytes of the 3MF file
  533. plate_number: Which plate was printed (1-based), or None for first plate
  534. include_positions: If True, return tuple of (objects dict, bbox_all)
  535. Returns:
  536. If include_positions=False: Dictionary mapping identify_id (int) to object name (str)
  537. If include_positions=True: Tuple of (dict mapping identify_id to {name, x, y}, bbox_all list or None)
  538. """
  539. from io import BytesIO
  540. printable_objects: dict = {}
  541. bbox_all: list | None = None
  542. try:
  543. with zipfile.ZipFile(BytesIO(data), "r") as zf:
  544. if "Metadata/slice_info.config" not in zf.namelist():
  545. return printable_objects
  546. content = zf.read("Metadata/slice_info.config").decode()
  547. root = ET.fromstring(content)
  548. plates = root.findall(".//plate")
  549. if not plates:
  550. return printable_objects
  551. # Pick the plate that is actually printing. An all-plates export
  552. # lists every plate, so without this we offered the objects (and
  553. # the marker positions) of plate 1 whatever the printer was
  554. # running (#2522). Falling back to the first plate keeps the
  555. # single-plate export — the common case — working when the caller
  556. # has no plate to give us.
  557. plate = None
  558. if plate_number is not None:
  559. plate = next((p for p in plates if _read_plate_index(p) == plate_number), None)
  560. if plate is None:
  561. plate = plates[0]
  562. # Derive plate_idx from the plate we settled on, never from the
  563. # requested one: on a fallback they differ, and plate_idx also
  564. # selects the plate_N.json the positions come from.
  565. plate_idx = _read_plate_index(plate) or 1
  566. # Load position data from plate_N.json if we need positions
  567. # Build a lookup by name - use list to handle duplicate names
  568. bbox_by_name: dict[str, list[list]] = {}
  569. if include_positions:
  570. plate_json_path = f"Metadata/plate_{plate_idx}.json"
  571. if plate_json_path in zf.namelist():
  572. try:
  573. plate_json = json.loads(zf.read(plate_json_path).decode())
  574. # Get bbox_all - the bounding box of all objects (used for image bounds)
  575. bbox_all = plate_json.get("bbox_all")
  576. for bbox_obj in plate_json.get("bbox_objects", []):
  577. obj_name = bbox_obj.get("name")
  578. bbox = bbox_obj.get("bbox", [])
  579. if obj_name and len(bbox) >= 4:
  580. if obj_name not in bbox_by_name:
  581. bbox_by_name[obj_name] = []
  582. bbox_by_name[obj_name].append(bbox)
  583. except (json.JSONDecodeError, KeyError):
  584. pass # Position data is optional; objects will lack x/y coordinates
  585. # Extract objects from slice_info.config
  586. for obj in plate.findall("object"):
  587. identify_id = obj.get("identify_id")
  588. name = obj.get("name")
  589. skipped = obj.get("skipped", "false")
  590. if identify_id and name and skipped.lower() != "true":
  591. try:
  592. obj_id = int(identify_id)
  593. if include_positions:
  594. x, y = None, None
  595. # Match by name - pop first bbox to handle duplicates
  596. bboxes = bbox_by_name.get(name)
  597. if bboxes:
  598. bbox = bboxes.pop(0)
  599. # Calculate center from bbox [x_min, y_min, x_max, y_max]
  600. x = (bbox[0] + bbox[2]) / 2
  601. y = (bbox[1] + bbox[3]) / 2
  602. printable_objects[obj_id] = {"name": name, "x": x, "y": y}
  603. else:
  604. printable_objects[obj_id] = name
  605. except ValueError:
  606. pass # Skip objects with non-numeric identify_id
  607. except Exception:
  608. pass # Return empty dict if 3MF is corrupt or unreadable
  609. if include_positions:
  610. return printable_objects, bbox_all
  611. return printable_objects
  612. class ProjectPageParser:
  613. """Parser for extracting project page data from Bambu Lab 3MF files."""
  614. def __init__(self, file_path: Path):
  615. self.file_path = file_path
  616. def parse(self, archive_id: int) -> dict:
  617. """Extract project page metadata and images from 3MF file."""
  618. import html
  619. result = {
  620. "title": None,
  621. "description": None,
  622. "designer": None,
  623. "designer_user_id": None,
  624. "license": None,
  625. "copyright": None,
  626. "creation_date": None,
  627. "modification_date": None,
  628. "origin": None,
  629. "profile_title": None,
  630. "profile_description": None,
  631. "profile_cover": None,
  632. "profile_user_id": None,
  633. "profile_user_name": None,
  634. "design_model_id": None,
  635. "design_profile_id": None,
  636. "design_region": None,
  637. "model_pictures": [],
  638. "profile_pictures": [],
  639. "thumbnails": [],
  640. }
  641. try:
  642. with zipfile.ZipFile(self.file_path, "r") as zf:
  643. # Parse 3D/3dmodel.model for metadata
  644. model_path = "3D/3dmodel.model"
  645. if model_path in zf.namelist():
  646. content = zf.read(model_path).decode("utf-8", errors="ignore")
  647. # Extract metadata elements using regex
  648. # Format: <metadata name="Key">Value</metadata> or <metadata name="Key" />
  649. metadata_pattern = r'<metadata\s+name="([^"]+)"[^>]*>([^<]*)</metadata>'
  650. matches = re.findall(metadata_pattern, content)
  651. field_mapping = {
  652. "Title": "title",
  653. "Description": "description",
  654. "Designer": "designer",
  655. "DesignerUserId": "designer_user_id",
  656. "License": "license",
  657. "Copyright": "copyright",
  658. "CreationDate": "creation_date",
  659. "ModificationDate": "modification_date",
  660. "Origin": "origin",
  661. "ProfileTitle": "profile_title",
  662. "ProfileDescription": "profile_description",
  663. "ProfileCover": "profile_cover",
  664. "ProfileUserId": "profile_user_id",
  665. "ProfileUserName": "profile_user_name",
  666. "DesignModelId": "design_model_id",
  667. "DesignProfileId": "design_profile_id",
  668. "DesignRegion": "design_region",
  669. }
  670. for name, value in matches:
  671. if name in field_mapping:
  672. # Decode HTML entities multiple times (content is often triple-encoded)
  673. decoded = value.strip()
  674. prev = None
  675. while prev != decoded:
  676. prev = decoded
  677. decoded = html.unescape(decoded)
  678. # Normalize non-breaking spaces to regular spaces
  679. decoded = decoded.replace("\xa0", " ")
  680. result[field_mapping[name]] = decoded if decoded else None
  681. # List images in Auxiliaries folder
  682. from urllib.parse import quote
  683. for name in zf.namelist():
  684. if name.startswith("Auxiliaries/Model Pictures/"):
  685. filename = name.split("/")[-1]
  686. if filename:
  687. result["model_pictures"].append(
  688. {
  689. "name": filename,
  690. "path": name,
  691. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  692. }
  693. )
  694. elif name.startswith("Auxiliaries/Profile Pictures/"):
  695. filename = name.split("/")[-1]
  696. if filename:
  697. result["profile_pictures"].append(
  698. {
  699. "name": filename,
  700. "path": name,
  701. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  702. }
  703. )
  704. elif name.startswith("Auxiliaries/.thumbnails/"):
  705. filename = name.split("/")[-1]
  706. if filename:
  707. result["thumbnails"].append(
  708. {
  709. "name": filename,
  710. "path": name,
  711. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  712. }
  713. )
  714. except Exception as e:
  715. result["_error"] = str(e)
  716. return result
  717. def get_image(self, image_path: str) -> tuple[bytes, str] | None:
  718. """Extract an image from the 3MF file.
  719. Returns tuple of (image_data, content_type) or None if not found.
  720. """
  721. try:
  722. with zipfile.ZipFile(self.file_path, "r") as zf:
  723. if image_path in zf.namelist():
  724. data = zf.read(image_path)
  725. # Determine content type from extension
  726. ext = image_path.lower().split(".")[-1]
  727. content_types = {
  728. "png": "image/png",
  729. "jpg": "image/jpeg",
  730. "jpeg": "image/jpeg",
  731. "webp": "image/webp",
  732. "gif": "image/gif",
  733. }
  734. content_type = content_types.get(ext, "application/octet-stream")
  735. return (data, content_type)
  736. except Exception:
  737. pass # Return None if image cannot be extracted from 3MF
  738. return None
  739. def update_metadata(self, updates: dict) -> bool:
  740. """Update project page metadata in the 3MF file.
  741. Args:
  742. updates: Dict with fields to update (title, description, designer, etc.)
  743. Returns:
  744. True if successful, False otherwise.
  745. """
  746. import html
  747. import tempfile
  748. try:
  749. # Read the 3MF file
  750. with zipfile.ZipFile(self.file_path, "r") as zf_read:
  751. # Find and read the 3dmodel.model file
  752. model_path = "3D/3dmodel.model"
  753. if model_path not in zf_read.namelist():
  754. return False
  755. content = zf_read.read(model_path).decode("utf-8")
  756. # Update metadata fields
  757. field_mapping = {
  758. "title": "Title",
  759. "description": "Description",
  760. "designer": "Designer",
  761. "license": "License",
  762. "copyright": "Copyright",
  763. "profile_title": "ProfileTitle",
  764. "profile_description": "ProfileDescription",
  765. }
  766. for field, xml_name in field_mapping.items():
  767. if field in updates and updates[field] is not None:
  768. new_value = html.escape(updates[field])
  769. # Replace existing metadata or we'd need to add it
  770. pattern = rf'(<metadata\s+name="{xml_name}"[^>]*>)[^<]*(</metadata>)'
  771. replacement = rf"\g<1>{new_value}\g<2>"
  772. content = re.sub(pattern, replacement, content)
  773. # Write to a temporary file first
  774. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf") as tmp:
  775. tmp_path = Path(tmp.name)
  776. # Create new zip with updated content
  777. with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as zf_write:
  778. for item in zf_read.namelist():
  779. if item == model_path:
  780. zf_write.writestr(item, content.encode("utf-8"))
  781. else:
  782. zf_write.writestr(item, zf_read.read(item))
  783. # Replace original file with updated one
  784. shutil.move(tmp_path, self.file_path)
  785. return True
  786. except Exception:
  787. # Clean up temp file if it exists
  788. if "tmp_path" in locals() and tmp_path.exists():
  789. tmp_path.unlink()
  790. return False
  791. async def _null_print_log_thumbnail_paths(db: AsyncSession, archive_id: int) -> None:
  792. """NULL thumbnail_path on PrintLogEntry rows linked to *archive_id*.
  793. Called from both soft- and hard-delete paths before the archive's files
  794. leave disk. The FK on PrintLogEntry.archive_id is ON DELETE SET NULL so
  795. log rows survive the archive — without this clear, their cached
  796. thumbnail_path would still point at a deleted file and the print-log
  797. view would 404-storm on every render (#1348 follow-up). Lazy-NULL on
  798. the GET route self-heals stragglers (e.g. failed prints that never had
  799. a thumbnail written), but eager clear here avoids the one-time storm.
  800. """
  801. from sqlalchemy import update as sa_update
  802. from backend.app.models.print_log import PrintLogEntry
  803. await db.execute(sa_update(PrintLogEntry).where(PrintLogEntry.archive_id == archive_id).values(thumbnail_path=None))
  804. async def _delete_related_queue_items(db: AsyncSession, archive_id: int) -> int:
  805. """Delete every queue item pointing at *archive_id* (#1734).
  806. Called from ``soft_delete_archive``. Hard-delete is covered by the
  807. ``ON DELETE CASCADE`` on ``print_queue.archive_id`` — same end state
  808. via the FK. Pre-#1734 this helper merely flipped pending rows to
  809. ``status='cancelled'`` while leaving every other status alone and
  810. leaving the rows in the DB, which surprised users who expected the
  811. queue lines to disappear when their backing archive went away. Worse,
  812. a Send-All archive backed N queue items (one per plate, #1733) — soft-
  813. deleting that archive left N "cancelled" rows behind, none of which
  814. could ever dispatch.
  815. Now we delete unconditionally regardless of status. ``printing`` rows
  816. are blocked one layer up at the route (``delete_archive`` returns 409
  817. when a related row is mid-print) so we never delete an actively-
  818. running queue row out from under the dispatcher. Completed / failed
  819. / cancelled rows go too — they're queue history, not print history.
  820. PrintLogEntry rows are the authoritative print history and are
  821. untouched (FK ``ON DELETE SET NULL``).
  822. Returns the number of rows removed so the caller can report it.
  823. """
  824. from sqlalchemy import delete as sa_delete
  825. from backend.app.models.print_queue import PrintQueueItem
  826. result = await db.execute(sa_delete(PrintQueueItem).where(PrintQueueItem.archive_id == archive_id))
  827. return result.rowcount or 0
  828. async def _count_related_queue_items(db: AsyncSession, archive_id: int) -> tuple[int, int]:
  829. """Return ``(total, printing)`` queue items linked to *archive_id*.
  830. Used by the archive GET response so the frontend delete-confirm modal
  831. can surface how much the deletion will wipe out, and by the delete
  832. route so it can 409 when a related row is currently printing (#1734).
  833. """
  834. from sqlalchemy import func as sa_func, select as sa_select
  835. from backend.app.models.print_queue import PrintQueueItem
  836. total = (
  837. await db.execute(
  838. sa_select(sa_func.count()).select_from(PrintQueueItem).where(PrintQueueItem.archive_id == archive_id)
  839. )
  840. ).scalar_one()
  841. printing = (
  842. await db.execute(
  843. sa_select(sa_func.count())
  844. .select_from(PrintQueueItem)
  845. .where(
  846. PrintQueueItem.archive_id == archive_id,
  847. PrintQueueItem.status == "printing",
  848. )
  849. )
  850. ).scalar_one()
  851. return int(total or 0), int(printing or 0)
  852. class ArchiveService:
  853. """Service for archiving print jobs."""
  854. def __init__(self, db: AsyncSession):
  855. self.db = db
  856. @staticmethod
  857. def compute_file_hash(file_path: Path) -> str:
  858. """Compute SHA256 hash of a file for duplicate detection."""
  859. sha256 = hashlib.sha256()
  860. with open(file_path, "rb") as f:
  861. # Read in chunks to handle large files
  862. for chunk in iter(lambda: f.read(8192), b""):
  863. sha256.update(chunk)
  864. return sha256.hexdigest()
  865. async def get_duplicate_hashes_and_names(self) -> tuple[set[str], set[tuple[str, str]]]:
  866. """Get all content hashes and (print name, hash) pairs that appear more than once.
  867. For hashes: returns all hashes with > 1 archive (true duplicates).
  868. For name/hash pairs: returns only pairs that have > 1 archive
  869. (i.e., same file archived multiple times, not different files with same name).
  870. Returns a tuple of (duplicate_hashes, duplicate_name_hash_pairs).
  871. """
  872. from sqlalchemy import func
  873. # Soft-deleted archives don't appear in the listing (#1343), so they
  874. # mustn't influence the duplicate-group counts either — otherwise a
  875. # group with 1 live + 4 soft-deleted would still be flagged as a
  876. # duplicate even though the user only sees one row.
  877. result = await self.db.execute(
  878. select(PrintArchive.content_hash)
  879. .where(PrintArchive.content_hash.isnot(None), PrintArchive.deleted_at.is_(None))
  880. .group_by(PrintArchive.content_hash)
  881. .having(func.count(PrintArchive.id) > 1)
  882. )
  883. duplicate_hashes = {row[0] for row in result.all()}
  884. # Find print names that have multiple archives with the SAME hash
  885. # This avoids marking different files with the same name as duplicates
  886. result = await self.db.execute(
  887. select(func.lower(PrintArchive.print_name), PrintArchive.content_hash)
  888. .where(
  889. PrintArchive.print_name.isnot(None),
  890. PrintArchive.content_hash.isnot(None),
  891. PrintArchive.deleted_at.is_(None),
  892. )
  893. .group_by(func.lower(PrintArchive.print_name), PrintArchive.content_hash)
  894. .having(func.count(PrintArchive.id) > 1)
  895. )
  896. duplicate_name_hash_pairs = {(row[0], row[1]) for row in result.all()}
  897. return duplicate_hashes, duplicate_name_hash_pairs
  898. async def find_duplicates(
  899. self,
  900. archive_id: int,
  901. content_hash: str | None = None,
  902. print_name: str | None = None,
  903. makerworld_model_id: str | None = None,
  904. ) -> list[dict]:
  905. """Find duplicate archives based on hash or name matching.
  906. Returns list of dicts with id, print_name, created_at, match_type.
  907. """
  908. duplicates = []
  909. # First, find exact matches by content hash
  910. if content_hash:
  911. result = await self.db.execute(
  912. select(PrintArchive)
  913. .where(
  914. and_(
  915. PrintArchive.content_hash == content_hash,
  916. PrintArchive.id != archive_id,
  917. PrintArchive.deleted_at.is_(None),
  918. )
  919. )
  920. .order_by(PrintArchive.created_at.desc())
  921. .limit(10)
  922. )
  923. for archive in result.scalars().all():
  924. duplicates.append(
  925. {
  926. "id": archive.id,
  927. "print_name": archive.print_name,
  928. "created_at": archive.created_at,
  929. "match_type": "exact",
  930. }
  931. )
  932. # Then, find similar matches by print name or MakerWorld ID
  933. # Prefer strict name+hash matching when hash exists; fallback to name-only for legacy/manual
  934. # archives that may not have a content_hash.
  935. if print_name or makerworld_model_id:
  936. conditions = [PrintArchive.id != archive_id, PrintArchive.deleted_at.is_(None)]
  937. name_conditions = []
  938. if print_name:
  939. if content_hash:
  940. # Match if print names are similar AND have the same hash (same file)
  941. name_conditions.append(
  942. and_(PrintArchive.print_name.ilike(print_name), PrintArchive.content_hash == content_hash)
  943. )
  944. else:
  945. # Fallback for archives without hash data: match by print name only.
  946. name_conditions.append(PrintArchive.print_name.ilike(print_name))
  947. if makerworld_model_id:
  948. # Match by MakerWorld model ID stored in extra_data
  949. from backend.app.core.db_dialect import is_sqlite
  950. if is_sqlite():
  951. from sqlalchemy import func
  952. name_conditions.append(
  953. func.json_extract(PrintArchive.extra_data, "$.makerworld_model_id") == str(makerworld_model_id)
  954. )
  955. else:
  956. name_conditions.append(
  957. text("(extra_data::jsonb->>'makerworld_model_id') = :mw_id").bindparams(
  958. mw_id=str(makerworld_model_id)
  959. )
  960. )
  961. if name_conditions:
  962. conditions.append(or_(*name_conditions))
  963. result = await self.db.execute(
  964. select(PrintArchive).where(and_(*conditions)).order_by(PrintArchive.created_at.desc()).limit(10)
  965. )
  966. for archive in result.scalars().all():
  967. # Don't add if already in duplicates (exact match)
  968. if not any(d["id"] == archive.id for d in duplicates):
  969. duplicates.append(
  970. {
  971. "id": archive.id,
  972. "print_name": archive.print_name,
  973. "created_at": archive.created_at,
  974. "match_type": "similar",
  975. }
  976. )
  977. return duplicates
  978. async def archive_print(
  979. self,
  980. printer_id: int | None,
  981. source_file: Path,
  982. print_data: dict | None = None,
  983. created_by_id: int | None = None,
  984. original_filename: str | None = None,
  985. project_id: int | None = None,
  986. cost_center_id: int | None = None,
  987. subtask_id: str | None = None,
  988. prefer_filename_for_name: bool = False,
  989. plate_id: int | None = None,
  990. library_file_id: int | None = None,
  991. slicer_ams_mapping: list[int] | None = None,
  992. slicer_ams_mapping_printer_id: int | None = None,
  993. ) -> PrintArchive | None:
  994. """Archive a 3MF file with metadata.
  995. Args:
  996. printer_id: ID of the printer (optional)
  997. source_file: Path to the 3MF file
  998. print_data: Print data from MQTT (optional)
  999. created_by_id: User ID who created this archive (optional, for user tracking)
  1000. original_filename: Original human-readable filename (optional, for library files
  1001. stored with UUID names)
  1002. project_id: Project to associate this archive with (optional, set when triggered
  1003. from the project view)
  1004. library_file_id: Library file this run was dispatched from (optional,
  1005. set by the queue scheduler — powers per-file project progress, #1897)
  1006. subtask_id: MQTT-provided task identifier (optional). Used to match an
  1007. existing archive across a backend restart mid-print so the
  1008. original row can be resumed instead of cancelled (#972).
  1009. prefer_filename_for_name: When True, use the uploaded filename stem as the
  1010. archive's display name even if the 3MF embeds a `print_name` in its
  1011. metadata. Used by virtual-printer flows so users who rename a job in
  1012. BambuStudio's "send to printer" dialog see that name instead of the
  1013. creator-baked title (#1152).
  1014. slicer_ams_mapping: The slicer's own live-resolved AMS-slot pick, to persist
  1015. onto `extra_data.slicer_ams_mapping` for a later reprint to reuse. Deliberately
  1016. a distinct parameter, not read off `print_data["ams_mapping"]` — that key is
  1017. populated on every MQTT print-start callback regardless of source (bambu_mqtt's
  1018. request-topic interception captures it for slicer-direct LAN prints too), so
  1019. promoting it unconditionally would stamp every archive on installs with no
  1020. virtual printer at all. Callers that gate this behind an opt-in (the VP-queue
  1021. "Save AMS mapping" toggle) pass it explicitly; everyone else leaves it unset.
  1022. slicer_ams_mapping_printer_id: The printer `slicer_ams_mapping`'s tray IDs were
  1023. resolved against. Required alongside `slicer_ams_mapping` — a global tray ID
  1024. only means something relative to one printer's specific AMS layout, so a
  1025. mapping saved without knowing which printer it came from can't be safely
  1026. reused later on any printer, including the same one (there'd be no way to
  1027. tell). A model-based VP with no fixed target printer has no valid value to
  1028. pass here and must leave both params unset.
  1029. """
  1030. # Verify printer exists if specified
  1031. if printer_id is not None:
  1032. result = await self.db.execute(select(Printer).where(Printer.id == printer_id))
  1033. printer = result.scalar_one_or_none()
  1034. if not printer:
  1035. return None
  1036. # Create archive directory structure
  1037. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1038. display_stem = resolve_display_stem(original_filename if original_filename else source_file.name)
  1039. archive_name = f"{timestamp}_{display_stem}"
  1040. # Use "unassigned" folder for archives without a printer
  1041. printer_folder = str(printer_id) if printer_id is not None else "unassigned"
  1042. archive_dir = (
  1043. settings.archive_dir / printer_folder / archive_name
  1044. ) # SEC-PATH-OK: printer_folder = str(int|None) → digits or "unassigned"; archive_name = f"{timestamp}_{display_stem}" where resolve_display_stem strips path components via Path(filename).name
  1045. archive_dir.mkdir(parents=True, exist_ok=True)
  1046. # Copy 3MF file with an explicit fsync'd loop (avoids a sendfile
  1047. # short-read quirk that silently truncated 3MF archives on some
  1048. # platforms — see _copy_and_fsync and #1032).
  1049. dest_file = archive_dir / source_file.name
  1050. _copy_and_fsync(source_file, dest_file)
  1051. # If we just archived a 3MF, verify the dest is a valid ZIP before
  1052. # going any further. Staying quiet here is how #1032 escaped review —
  1053. # the archive row was written but every later zipfile.ZipFile() call
  1054. # on the dest failed with "File is not a zip file".
  1055. if (
  1056. source_file.suffix.lower() == ".3mf"
  1057. and zipfile.is_zipfile(source_file)
  1058. and not zipfile.is_zipfile(dest_file)
  1059. ):
  1060. try:
  1061. src_size = source_file.stat().st_size
  1062. dst_size = dest_file.stat().st_size
  1063. except OSError:
  1064. src_size = dst_size = -1
  1065. logger.error(
  1066. "Archive copy corrupted 3MF: src=%s (%s bytes, valid ZIP) -> dst=%s (%s bytes, NOT a ZIP). Refusing to create archive row.",
  1067. source_file,
  1068. src_size,
  1069. dest_file,
  1070. dst_size,
  1071. )
  1072. # Narrow cleanup: remove only the truncated file and the archive
  1073. # directory if it's now empty. archive_dir was created with
  1074. # exist_ok=True so it could in theory pre-date this call (e.g.
  1075. # same-second same-filename collision); rmtree would be too broad.
  1076. try:
  1077. dest_file.unlink()
  1078. except OSError:
  1079. pass
  1080. try:
  1081. archive_dir.rmdir()
  1082. except OSError:
  1083. pass # directory not empty — leave untouched
  1084. return None
  1085. # Compute content hash for duplicate detection
  1086. content_hash = self.compute_file_hash(dest_file)
  1087. # Extract plate number from filename (e.g., "plate_5" from "/data/Metadata/plate_5.gcode")
  1088. plate_number = None
  1089. if print_data:
  1090. filename = print_data.get("filename", "")
  1091. match = re.search(r"plate_(\d+)", filename)
  1092. if match:
  1093. plate_number = int(match.group(1))
  1094. # Parse 3MF metadata
  1095. parser = ThreeMFParser(dest_file, plate_number=plate_number)
  1096. metadata = parser.parse()
  1097. # Save thumbnail if present
  1098. thumbnail_path = None
  1099. if "_thumbnail_data" in metadata:
  1100. thumb_file = archive_dir / f"thumbnail{metadata['_thumbnail_ext']}"
  1101. thumb_file.write_bytes(metadata["_thumbnail_data"])
  1102. thumbnail_path = str(thumb_file.relative_to(settings.base_dir))
  1103. del metadata["_thumbnail_data"]
  1104. del metadata["_thumbnail_ext"]
  1105. # Merge with print data from MQTT
  1106. if print_data:
  1107. metadata["_print_data"] = print_data
  1108. # Promote the slicer's own live-resolved AMS-slot pick, when the caller
  1109. # explicitly opted in (see the `slicer_ams_mapping` param docstring for
  1110. # why this is NOT read off `print_data["ams_mapping"]`), to a stable
  1111. # top-level extra_data key. Lets a later reprint reuse the exact tray
  1112. # the user picked/BambuStudio auto-matched at slice time instead of the
  1113. # scheduler re-deriving one from just the file's static type/color,
  1114. # which can land on the wrong physical spool when that match isn't
  1115. # unique. Top-level (not nested under the `_print_data` diagnostic bag)
  1116. # so API consumers have a single stable path:
  1117. # `archive.extra_data.slicer_ams_mapping`. Stored together with the
  1118. # printer it was resolved against — see `slicer_ams_mapping_printer_id`
  1119. # param docstring — so a later reprint can tell whether it's even
  1120. # applicable before trying to reuse it.
  1121. if slicer_ams_mapping and slicer_ams_mapping_printer_id is not None:
  1122. metadata["slicer_ams_mapping"] = {
  1123. "mapping": slicer_ams_mapping,
  1124. "printer_id": slicer_ams_mapping_printer_id,
  1125. }
  1126. # Determine status and timestamps
  1127. status = print_data.get("status", "completed") if print_data else "archived"
  1128. started_at = datetime.now(timezone.utc) if status == "printing" else None
  1129. completed_at = datetime.now(timezone.utc) if status in ("completed", "failed", "archived") else None
  1130. # Calculate cost based on filament usage and type
  1131. cost = None
  1132. filament_grams = metadata.get("filament_used_grams")
  1133. filament_type = metadata.get("filament_type")
  1134. if filament_grams and filament_type:
  1135. # For multi-material prints, use the first filament type for cost calculation
  1136. primary_type = filament_type.split(",")[0].strip()
  1137. # Look up filament cost_per_kg from database
  1138. filament_result = await self.db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  1139. filament = filament_result.scalar_one_or_none()
  1140. if filament:
  1141. cost = round((filament_grams / 1000) * filament.cost_per_kg, 2)
  1142. else:
  1143. # Use default filament cost from settings
  1144. from backend.app.api.routes.settings import get_setting
  1145. default_cost_setting = await get_setting(self.db, "default_filament_cost")
  1146. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1147. cost = round((filament_grams / 1000) * default_cost_per_kg, 2)
  1148. # Calculate quantity from printable objects count
  1149. # printable_objects is a dict of {identify_id: name} for non-skipped objects
  1150. quantity = 1 # Default to 1
  1151. printable_objects = metadata.get("printable_objects")
  1152. if printable_objects and isinstance(printable_objects, dict):
  1153. quantity = len(printable_objects)
  1154. logger.debug("Auto-detected %s parts from 3MF printable objects", quantity)
  1155. # Create archive record
  1156. archive = PrintArchive(
  1157. printer_id=printer_id,
  1158. filename=original_filename or source_file.name,
  1159. file_path=str(dest_file.relative_to(settings.base_dir)),
  1160. file_size=dest_file.stat().st_size,
  1161. content_hash=content_hash,
  1162. thumbnail_path=thumbnail_path,
  1163. # clean_display_name because the 3MF's own metadata reaches this
  1164. # verbatim, and a control character in it renders nowhere and
  1165. # truncates somewhere (#2832). The schema does the same for names
  1166. # arriving over the API. Cleaned before the fallback rather than
  1167. # after it, so an embedded name that is only whitespace still falls
  1168. # through to the filename instead of leaving the archive nameless.
  1169. print_name=(
  1170. clean_display_name(display_stem)
  1171. if prefer_filename_for_name
  1172. else (clean_display_name(metadata.get("print_name")) or clean_display_name(display_stem))
  1173. ),
  1174. print_time_seconds=metadata.get("print_time_seconds"),
  1175. filament_used_grams=metadata.get("filament_used_grams"),
  1176. filament_type=metadata.get("filament_type"),
  1177. filament_color=metadata.get("filament_color"),
  1178. layer_height=metadata.get("layer_height"),
  1179. total_layers=metadata.get("total_layers"),
  1180. nozzle_diameter=metadata.get("nozzle_diameter"),
  1181. bed_temperature=metadata.get("bed_temperature"),
  1182. bed_type=metadata.get("bed_type"),
  1183. nozzle_temperature=metadata.get("nozzle_temperature"),
  1184. sliced_for_model=metadata.get("sliced_for_model"),
  1185. makerworld_url=metadata.get("makerworld_url"),
  1186. designer=metadata.get("designer"),
  1187. status=status,
  1188. started_at=started_at,
  1189. completed_at=completed_at,
  1190. cost=cost,
  1191. quantity=quantity,
  1192. extra_data=metadata,
  1193. created_by_id=created_by_id,
  1194. project_id=project_id,
  1195. library_file_id=library_file_id,
  1196. cost_center_id=cost_center_id,
  1197. subtask_id=subtask_id,
  1198. plate_id=plate_id,
  1199. )
  1200. self.db.add(archive)
  1201. await self.db.commit()
  1202. await self.db.refresh(archive)
  1203. return archive
  1204. async def get_archive(self, archive_id: int) -> PrintArchive | None:
  1205. """Get an archive by ID with relationships loaded."""
  1206. from sqlalchemy.orm import selectinload
  1207. result = await self.db.execute(
  1208. select(PrintArchive)
  1209. .options(selectinload(PrintArchive.created_by), selectinload(PrintArchive.project))
  1210. .where(PrintArchive.id == archive_id)
  1211. )
  1212. return result.scalar_one_or_none()
  1213. async def update_archive_status(
  1214. self,
  1215. archive_id: int,
  1216. status: str,
  1217. completed_at: datetime | None = None,
  1218. failure_reason: str | None = None,
  1219. ) -> bool:
  1220. """Update the status of an archive."""
  1221. archive = await self.get_archive(archive_id)
  1222. if not archive:
  1223. return False
  1224. archive.status = status
  1225. if completed_at:
  1226. archive.completed_at = completed_at
  1227. if failure_reason:
  1228. archive.failure_reason = failure_reason
  1229. await self.db.commit()
  1230. return True
  1231. async def list_archives(
  1232. self,
  1233. printer_id: int | None = None,
  1234. project_id: int | None = None,
  1235. date_from: date | None = None,
  1236. date_to: date | None = None,
  1237. limit: int = 50,
  1238. offset: int = 0,
  1239. visible_to_user_id: int | None = None,
  1240. ) -> list[PrintArchive]:
  1241. """List archives with optional filtering.
  1242. ``visible_to_user_id`` scopes results to archives that user owns. Used
  1243. when the caller has ARCHIVES_READ_OWN but not ARCHIVES_READ_ALL — pass
  1244. ``None`` to skip the filter (caller has read-all or auth is disabled).
  1245. """
  1246. from sqlalchemy.orm import selectinload
  1247. query = (
  1248. select(PrintArchive)
  1249. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1250. # Hide soft-deleted rows from the listings (#1343). The stats
  1251. # endpoint deliberately does NOT add this filter so deleted
  1252. # archives keep contributing to Quick Stats.
  1253. .where(PrintArchive.deleted_at.is_(None))
  1254. .order_by(PrintArchive.created_at.desc())
  1255. )
  1256. if printer_id:
  1257. query = query.where(PrintArchive.printer_id == printer_id)
  1258. if project_id:
  1259. query = query.where(PrintArchive.project_id == project_id)
  1260. if date_from:
  1261. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  1262. query = query.where(PrintArchive.created_at >= dt_from)
  1263. if date_to:
  1264. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  1265. query = query.where(PrintArchive.created_at <= dt_to)
  1266. if visible_to_user_id is not None:
  1267. query = query.where(PrintArchive.created_by_id == visible_to_user_id)
  1268. query = query.limit(limit).offset(offset)
  1269. result = await self.db.execute(query)
  1270. return list(result.scalars().all())
  1271. async def soft_delete_archive(self, archive_id: int) -> bool:
  1272. """Soft-delete an archive (#1343).
  1273. Removes the archive's files from disk (it disappears from the listings
  1274. and frees the storage) but flips the row's ``deleted_at`` so the stats
  1275. endpoint keeps counting its filament / energy / time / cost. The user
  1276. can opt into a hard delete via the "Also remove from statistics"
  1277. checkbox in the delete dialog — that path calls ``delete_archive``
  1278. instead and removes the row entirely.
  1279. """
  1280. archive = await self.get_archive(archive_id)
  1281. if not archive:
  1282. return False
  1283. if archive.deleted_at is not None:
  1284. # Already soft-deleted; nothing to do. The files were purged on
  1285. # the first soft-delete pass so there is nothing left on disk.
  1286. return True
  1287. dir_to_delete = self._resolve_archive_dir_for_delete(archive)
  1288. await _null_print_log_thumbnail_paths(self.db, archive_id)
  1289. await _delete_related_queue_items(self.db, archive_id)
  1290. archive.deleted_at = datetime.now(timezone.utc)
  1291. await self.db.commit()
  1292. if dir_to_delete:
  1293. shutil.rmtree(dir_to_delete, ignore_errors=True)
  1294. return True
  1295. def _resolve_archive_dir_for_delete(self, archive: PrintArchive) -> Path | None:
  1296. """Return the on-disk directory that backs *archive*, after the same
  1297. two safety checks ``delete_archive`` enforces.
  1298. Extracted so soft-delete and hard-delete share the path-resolution
  1299. rules. Returns ``None`` when nothing should be removed from disk
  1300. (no file_path, path outside archive_dir, or path not deep enough).
  1301. """
  1302. if not archive.file_path or not archive.file_path.strip():
  1303. logger.error(
  1304. f"SECURITY: Refusing to delete files for archive {archive.id} - "
  1305. f"file_path is empty or invalid: '{archive.file_path}'"
  1306. )
  1307. return None
  1308. file_path = settings.base_dir / archive.file_path
  1309. if not file_path.exists():
  1310. return None
  1311. archive_dir = file_path.parent
  1312. try:
  1313. relative_path = archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1314. except ValueError:
  1315. logger.error(
  1316. f"SECURITY: Refusing to delete archive {archive.id} - "
  1317. f"path {archive_dir} is outside archive directory {settings.archive_dir}"
  1318. )
  1319. return None
  1320. if len(relative_path.parts) < 1:
  1321. logger.error(
  1322. f"SECURITY: Refusing to delete archive {archive.id} - "
  1323. f"path {archive_dir} is not deep enough inside archive directory"
  1324. )
  1325. return None
  1326. return archive_dir
  1327. async def delete_archive(self, archive_id: int) -> bool:
  1328. """Delete an archive and its files."""
  1329. archive = await self.get_archive(archive_id)
  1330. if not archive:
  1331. return False
  1332. # Resolve the directory to delete BEFORE committing the DB change
  1333. dir_to_delete: Path | None = None
  1334. if archive.file_path and archive.file_path.strip():
  1335. file_path = settings.base_dir / archive.file_path
  1336. if file_path.exists():
  1337. archive_dir = file_path.parent
  1338. # Safety check 1: archive_dir must be inside archive_dir
  1339. try:
  1340. archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1341. except ValueError:
  1342. logger.error(
  1343. f"SECURITY: Refusing to delete archive {archive_id} - "
  1344. f"path {archive_dir} is outside archive directory {settings.archive_dir}"
  1345. )
  1346. await self.db.delete(archive)
  1347. await self.db.commit()
  1348. return True
  1349. # Safety check 2: archive_dir must be at least 1 level deep inside archive_dir
  1350. try:
  1351. relative_path = archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1352. if len(relative_path.parts) < 1:
  1353. logger.error(
  1354. f"SECURITY: Refusing to delete archive {archive_id} - "
  1355. f"path {archive_dir} is not deep enough inside archive directory"
  1356. )
  1357. await self.db.delete(archive)
  1358. await self.db.commit()
  1359. return True
  1360. except ValueError:
  1361. pass # Already handled above
  1362. dir_to_delete = archive_dir
  1363. else:
  1364. logger.error(
  1365. f"SECURITY: Refusing to delete files for archive {archive_id} - "
  1366. f"file_path is empty or invalid: '{archive.file_path}'"
  1367. )
  1368. # NULL stale thumbnail_path on linked PrintLogEntries before the FK
  1369. # SET-NULL cascade fires. The on-disk file is about to be removed by
  1370. # the rmtree below, so the path on any surviving log entry (archive_id
  1371. # gets SET NULL by the FK) would otherwise point at a missing file
  1372. # and produce 404 storms in the print-log view (#1348-followup).
  1373. await _null_print_log_thumbnail_paths(self.db, archive_id)
  1374. # Delete database record FIRST — if the commit fails (e.g. database locked
  1375. # during concurrent bulk deletes), the files stay on disk and nothing is lost.
  1376. await self.db.delete(archive)
  1377. await self.db.commit()
  1378. # Only delete files AFTER the DB commit succeeds to avoid orphaned records
  1379. if dir_to_delete:
  1380. shutil.rmtree(dir_to_delete, ignore_errors=True)
  1381. return True
  1382. async def attach_timelapse(
  1383. self,
  1384. archive_id: int,
  1385. timelapse_data: bytes,
  1386. filename: str = "timelapse.mp4",
  1387. ) -> bool:
  1388. """Attach a timelapse video to an archive.
  1389. Non-MP4 videos (e.g. AVI from P1S) are saved as-is and a background
  1390. task converts them to MP4 for browser compatibility.
  1391. """
  1392. import asyncio
  1393. archive = await self.get_archive(archive_id)
  1394. if not archive:
  1395. return False
  1396. # Where this archive's files live. Deliberately the shared helper: an
  1397. # archive created without a 3MF has ``file_path == ""``, and deriving the
  1398. # directory here as ``(base_dir / "").parent`` resolved to the parent of
  1399. # base_dir — outside the data directory entirely. In Docker that is /app,
  1400. # so the write failed with EACCES and the timelapse was retried and
  1401. # discarded 25 times; where the parent happens to be writable it
  1402. # succeeded, dropped a stray video next to the install, and then failed
  1403. # anyway on the relative_to() below. Every H2-series and P2S print sent
  1404. # from the slicer takes that path, because the file goes to internal
  1405. # storage and no 3MF can be fetched.
  1406. archive_dir = resolve_archive_dir(archive)
  1407. # Save timelapse - use thread pool to avoid blocking event loop
  1408. # (timelapse files can be 100MB+, sync write blocks for seconds).
  1409. # `filename` ultimately comes from a printer's FTP listing (compromised-
  1410. # printer threat model) or a query param on /archives/{id}/timelapse/select;
  1411. # the safe-join helper rejects ``..`` segments and absolute paths so a
  1412. # crafted name can't escape the archive directory. Use http=False so a
  1413. # service-layer reject surfaces as a return False (matching the existing
  1414. # not-found contract) rather than a 400 raised from inside a background
  1415. # task.
  1416. try:
  1417. timelapse_file = safe_join_under(archive_dir, filename, http=False)
  1418. except PathTraversalError:
  1419. logger.warning(
  1420. "Refusing to attach timelapse with unsafe filename %r to archive %s",
  1421. filename,
  1422. archive_id,
  1423. )
  1424. return False
  1425. # Created only once the name has been vetted, so a rejected filename
  1426. # leaves nothing behind. A no-3MF archive has never had a directory of
  1427. # its own, and the timelapse can be the first thing to want one.
  1428. await asyncio.to_thread(lambda: timelapse_file.parent.mkdir(parents=True, exist_ok=True))
  1429. await asyncio.to_thread(timelapse_file.write_bytes, timelapse_data)
  1430. # Update archive record
  1431. archive.timelapse_path = str(timelapse_file.relative_to(settings.base_dir))
  1432. await self.db.commit()
  1433. # For non-MP4 videos (e.g. AVI from P1S), kick off background conversion
  1434. if not filename.lower().endswith(".mp4"):
  1435. spawn_background_task(
  1436. _convert_timelapse_to_mp4(archive_id, timelapse_file),
  1437. name=f"timelapse-convert-{archive_id}",
  1438. )
  1439. return True
  1440. async def _convert_timelapse_to_mp4(archive_id: int, source_path: Path) -> None:
  1441. """Background task: convert non-MP4 timelapse (e.g. AVI from P1S) to MP4.
  1442. Runs with low CPU priority (-threads 1, nice) so it doesn't starve
  1443. other processes on resource-constrained devices like Raspberry Pi.
  1444. """
  1445. import asyncio
  1446. from backend.app.core.database import async_session
  1447. from backend.app.services.camera import get_ffmpeg_path
  1448. logger = logging.getLogger(__name__)
  1449. ffmpeg = get_ffmpeg_path()
  1450. if not ffmpeg:
  1451. logger.info(
  1452. "FFmpeg not available, skipping timelapse conversion for archive %s (file saved as %s)",
  1453. archive_id,
  1454. source_path.suffix,
  1455. )
  1456. return
  1457. mp4_path = source_path.with_suffix(".mp4")
  1458. try:
  1459. cmd = [
  1460. ffmpeg,
  1461. "-y",
  1462. "-i",
  1463. str(source_path),
  1464. "-c:v",
  1465. "libx264",
  1466. "-preset",
  1467. "fast",
  1468. "-crf",
  1469. "23",
  1470. "-threads",
  1471. "1",
  1472. "-movflags",
  1473. "+faststart",
  1474. str(mp4_path),
  1475. ]
  1476. # Try with nice for lower CPU priority (standard on Linux/macOS)
  1477. try:
  1478. process = await asyncio.create_subprocess_exec(
  1479. "nice",
  1480. "-n",
  1481. "19",
  1482. *cmd,
  1483. stdout=asyncio.subprocess.PIPE,
  1484. stderr=asyncio.subprocess.PIPE,
  1485. )
  1486. except FileNotFoundError:
  1487. # nice not available (e.g. Windows), run without
  1488. process = await asyncio.create_subprocess_exec(
  1489. *cmd,
  1490. stdout=asyncio.subprocess.PIPE,
  1491. stderr=asyncio.subprocess.PIPE,
  1492. )
  1493. _, stderr = await process.communicate()
  1494. if process.returncode != 0:
  1495. logger.warning(
  1496. "Timelapse conversion failed for archive %s: %s",
  1497. archive_id,
  1498. stderr.decode()[-500:],
  1499. )
  1500. if mp4_path.exists():
  1501. mp4_path.unlink()
  1502. return
  1503. # Update DB path to the new MP4 file
  1504. async with async_session() as db:
  1505. from backend.app.models.archive import PrintArchive
  1506. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1507. archive = result.scalar_one_or_none()
  1508. if archive:
  1509. archive.timelapse_path = str(mp4_path.relative_to(settings.base_dir))
  1510. await db.commit()
  1511. # Remove original non-MP4 file
  1512. if source_path.exists():
  1513. source_path.unlink()
  1514. logger.info(
  1515. "Converted timelapse to MP4 for archive %s (%s → %s)",
  1516. archive_id,
  1517. source_path.name,
  1518. mp4_path.name,
  1519. )
  1520. except Exception as e:
  1521. logger.warning("Timelapse conversion error for archive %s: %s", archive_id, e)
  1522. if mp4_path.exists():
  1523. mp4_path.unlink()