archive.py 66 KB

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