archive.py 76 KB

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