archive.py 77 KB

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