archive.py 73 KB

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