archive.py 67 KB

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