archive.py 73 KB

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