archive.py 70 KB

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