archive.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. import hashlib
  2. import json
  3. import logging
  4. import re
  5. import shutil
  6. import zipfile
  7. from datetime import datetime
  8. from pathlib import Path
  9. from defusedxml import ElementTree as ET
  10. from sqlalchemy import and_, or_, select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.core.config import settings
  13. from backend.app.models.archive import PrintArchive
  14. from backend.app.models.filament import Filament
  15. from backend.app.models.printer import Printer
  16. logger = logging.getLogger(__name__)
  17. class ThreeMFParser:
  18. """Parser for Bambu Lab 3MF files."""
  19. def __init__(self, file_path: Path, plate_number: int | None = None):
  20. self.file_path = file_path
  21. self.plate_number = plate_number # Which plate was printed (1, 2, 3, etc.)
  22. self.metadata: dict = {}
  23. def parse(self) -> dict:
  24. """Extract metadata from 3MF file."""
  25. try:
  26. with zipfile.ZipFile(self.file_path, "r") as zf:
  27. self._parse_slice_info(zf) # Now sets self.plate_number from slice_info
  28. self._parse_project_settings(zf)
  29. self._parse_gcode_header(zf)
  30. self._parse_3dmodel(zf)
  31. self._extract_thumbnail(zf) # Uses correct plate_number for thumbnail
  32. # Enhance print_name with plate info if this is a multi-plate export
  33. plate_index = self.metadata.get("_plate_index")
  34. if plate_index and plate_index > 1:
  35. # Append plate number to distinguish from other plates
  36. existing_name = self.metadata.get("print_name", "")
  37. if existing_name and f"Plate {plate_index}" not in existing_name:
  38. self.metadata["print_name"] = f"{existing_name} - Plate {plate_index}"
  39. # ALWAYS prefer slice_info values - they contain ONLY filaments actually used in print
  40. # project_settings contains ALL configured filaments (AMS slots), not just used ones
  41. if self.metadata.get("_slice_filament_type"):
  42. self.metadata["filament_type"] = self.metadata["_slice_filament_type"]
  43. if self.metadata.get("_slice_filament_color"):
  44. self.metadata["filament_color"] = self.metadata["_slice_filament_color"]
  45. # Clean up internal keys
  46. self.metadata.pop("_slice_filament_type", None)
  47. self.metadata.pop("_slice_filament_color", None)
  48. self.metadata.pop("_plate_index", None)
  49. except Exception:
  50. pass # Return whatever metadata was extracted before the error
  51. return self.metadata
  52. def _parse_slice_info(self, zf: zipfile.ZipFile):
  53. """Parse slice_info.config for print settings and printable objects."""
  54. try:
  55. if "Metadata/slice_info.config" in zf.namelist():
  56. content = zf.read("Metadata/slice_info.config").decode()
  57. root = ET.fromstring(content)
  58. # Extract printer_model_id from plate metadata
  59. # Format: <plate><metadata key="printer_model_id" value="C11" /></plate>
  60. for meta in root.findall(".//metadata"):
  61. key = meta.get("key")
  62. value = meta.get("value")
  63. if key == "printer_model_id" and value:
  64. from backend.app.utils.printer_models import normalize_printer_model_id
  65. normalized = normalize_printer_model_id(value)
  66. if normalized:
  67. self.metadata["sliced_for_model"] = normalized
  68. break
  69. # Find the plate element (single-plate exports only have one plate)
  70. plate = root.find(".//plate")
  71. if plate is not None:
  72. # Extract metadata from plate element
  73. for meta in plate.findall("metadata"):
  74. key = meta.get("key")
  75. value = meta.get("value")
  76. if key == "index" and value:
  77. # Extract plate index - this tells us which plate was exported
  78. try:
  79. extracted_index = int(value)
  80. # Set plate_number if not already set from filename
  81. if not self.plate_number:
  82. self.plate_number = extracted_index
  83. # Store in metadata for print_name generation
  84. self.metadata["_plate_index"] = extracted_index
  85. except ValueError:
  86. pass # Skip non-numeric plate index
  87. elif key == "prediction" and value:
  88. self.metadata["print_time_seconds"] = int(value)
  89. elif key == "weight" and value:
  90. self.metadata["filament_used_grams"] = float(value)
  91. # Extract printable objects for skip object functionality
  92. # Objects are stored as <object identify_id="123" name="Part1" skipped="false" />
  93. printable_objects = {}
  94. for obj in plate.findall("object"):
  95. identify_id = obj.get("identify_id")
  96. name = obj.get("name")
  97. skipped = obj.get("skipped", "false")
  98. # Only include objects that are not pre-skipped
  99. if identify_id and name and skipped.lower() != "true":
  100. try:
  101. printable_objects[int(identify_id)] = name
  102. except ValueError:
  103. pass # Skip objects with non-numeric identify_id
  104. if printable_objects:
  105. self.metadata["printable_objects"] = printable_objects
  106. # Get filament info from filaments ACTUALLY USED in the print
  107. # slice_info has <filament id="1" type="PLA" color="#FFFFFF" used_g="100" />
  108. # Only include filaments where used_g > 0
  109. filaments = root.findall(".//filament")
  110. if filaments:
  111. # Collect unique filament types and colors for filaments that are actually used
  112. types = []
  113. colors = []
  114. for f in filaments:
  115. # Check if this filament is actually used in the print
  116. used_g = f.get("used_g", "0")
  117. try:
  118. used_amount = float(used_g)
  119. except (ValueError, TypeError):
  120. used_amount = 0
  121. # Only include if used_g > 0 (filament is actually consumed)
  122. if used_amount > 0:
  123. ftype = f.get("type")
  124. fcolor = f.get("color")
  125. if ftype and ftype not in types:
  126. types.append(ftype)
  127. if fcolor and fcolor not in colors:
  128. colors.append(fcolor)
  129. if types:
  130. self.metadata["_slice_filament_type"] = ", ".join(types)
  131. if colors:
  132. self.metadata["_slice_filament_color"] = ",".join(colors)
  133. except Exception:
  134. pass # Skip unparseable slice_info metadata
  135. def _parse_project_settings(self, zf: zipfile.ZipFile):
  136. """Parse project settings for print configuration."""
  137. try:
  138. if "Metadata/project_settings.config" in zf.namelist():
  139. content = zf.read("Metadata/project_settings.config").decode()
  140. try:
  141. data = json.loads(content)
  142. self._extract_filament_info(data)
  143. self._extract_print_settings(data)
  144. except json.JSONDecodeError:
  145. pass # Skip malformed project_settings JSON
  146. except Exception:
  147. pass # Skip unreadable project settings file
  148. def _parse_gcode_header(self, zf: zipfile.ZipFile):
  149. """Parse G-code file header for total layer count and printer model."""
  150. try:
  151. # Look for plate_1.gcode or similar
  152. gcode_files = [f for f in zf.namelist() if f.endswith(".gcode")]
  153. if not gcode_files:
  154. return
  155. # Read first 4KB of G-code (header contains metadata)
  156. gcode_path = gcode_files[0]
  157. with zf.open(gcode_path) as f:
  158. header = f.read(4096).decode("utf-8", errors="ignore")
  159. # Look for "; total layer number: XX" pattern
  160. match = re.search(r";\s*total\s+layer\s+number[:\s]+(\d+)", header, re.IGNORECASE)
  161. if match:
  162. self.metadata["total_layers"] = int(match.group(1))
  163. # Look for printer_model in gcode header (fallback if not found in slice_info)
  164. # Format: "; printer_model = Bambu Lab X1 Carbon" or "; printer_model = X1C"
  165. if "sliced_for_model" not in self.metadata:
  166. match = re.search(r";\s*printer_model\s*=\s*(.+)", header, re.IGNORECASE)
  167. if match:
  168. from backend.app.utils.printer_models import normalize_printer_model
  169. raw_model = match.group(1).strip()
  170. self.metadata["sliced_for_model"] = normalize_printer_model(raw_model)
  171. except Exception:
  172. pass # G-code header parsing is best-effort; metadata may come from other sources
  173. def _extract_filament_info(self, data: dict):
  174. """Extract filament info, preferring non-support filaments."""
  175. try:
  176. filament_types = data.get("filament_type", [])
  177. filament_colors = data.get("filament_colour", [])
  178. filament_is_support = data.get("filament_is_support", [])
  179. if not filament_types:
  180. return
  181. # Collect all non-support filaments
  182. non_support_types = []
  183. non_support_colors = []
  184. for i, ftype in enumerate(filament_types):
  185. is_support = filament_is_support[i] if i < len(filament_is_support) else "0"
  186. if is_support == "0":
  187. if ftype and ftype not in non_support_types:
  188. non_support_types.append(ftype)
  189. if i < len(filament_colors) and filament_colors[i]:
  190. color = filament_colors[i]
  191. if color not in non_support_colors:
  192. non_support_colors.append(color)
  193. # Fallback to first filament if all are support
  194. if not non_support_types and filament_types:
  195. non_support_types = [filament_types[0]]
  196. if not non_support_colors and filament_colors:
  197. non_support_colors = [filament_colors[0]]
  198. # Store filament type(s)
  199. if non_support_types:
  200. self.metadata["filament_type"] = ", ".join(non_support_types)
  201. # Store all colors as comma-separated (for multi-color display)
  202. if non_support_colors:
  203. self.metadata["filament_color"] = ",".join(non_support_colors)
  204. except Exception:
  205. pass # Filament info is optional; fall back to slice_info values
  206. def _extract_print_settings(self, data: dict):
  207. """Extract print settings from JSON config."""
  208. try:
  209. # Layer height - usually an array, get first value
  210. if "layer_height" in data:
  211. val = data["layer_height"]
  212. if isinstance(val, list) and val:
  213. self.metadata["layer_height"] = float(val[0])
  214. elif isinstance(val, (int, float, str)):
  215. self.metadata["layer_height"] = float(val)
  216. # Nozzle diameter
  217. if "nozzle_diameter" in data:
  218. val = data["nozzle_diameter"]
  219. if isinstance(val, list) and val:
  220. self.metadata["nozzle_diameter"] = float(val[0])
  221. elif isinstance(val, (int, float, str)):
  222. self.metadata["nozzle_diameter"] = float(val)
  223. # Bed temperature - first layer or regular
  224. for key in ["bed_temperature_initial_layer", "bed_temperature"]:
  225. if key in data:
  226. val = data[key]
  227. if isinstance(val, list) and val:
  228. self.metadata["bed_temperature"] = int(float(val[0]))
  229. elif isinstance(val, (int, float, str)):
  230. self.metadata["bed_temperature"] = int(float(val))
  231. break
  232. # Nozzle temperature
  233. for key in ["nozzle_temperature_initial_layer", "nozzle_temperature"]:
  234. if key in data:
  235. val = data[key]
  236. if isinstance(val, list) and val:
  237. self.metadata["nozzle_temperature"] = int(float(val[0]))
  238. elif isinstance(val, (int, float, str)):
  239. self.metadata["nozzle_temperature"] = int(float(val))
  240. break
  241. # Printer model (extract and normalize)
  242. if "printer_model" in data:
  243. from backend.app.utils.printer_models import normalize_printer_model
  244. self.metadata["sliced_for_model"] = normalize_printer_model(data["printer_model"])
  245. except Exception:
  246. pass # Print settings are optional; missing values are left unset
  247. def _extract_settings_from_content(self, content: str):
  248. """Extract print settings from config content."""
  249. settings_map = {
  250. "layer_height": ("layer_height", float),
  251. "nozzle_diameter": ("nozzle_diameter", float),
  252. "bed_temperature": ("bed_temperature", int),
  253. "nozzle_temperature": ("nozzle_temperature", int),
  254. }
  255. for key, (search_key, converter) in settings_map.items():
  256. if key not in self.metadata:
  257. try:
  258. # Try JSON format
  259. if f'"{search_key}"' in content:
  260. start = content.find(f'"{search_key}"')
  261. value_start = content.find(":", start) + 1
  262. value_end = content.find(",", value_start)
  263. if value_end == -1:
  264. value_end = content.find("}", value_start)
  265. value = content[value_start:value_end].strip().strip('"')
  266. self.metadata[key] = converter(value)
  267. except (ValueError, TypeError):
  268. pass # Skip settings with unconvertible values
  269. def _parse_3dmodel(self, zf: zipfile.ZipFile):
  270. """Parse 3D/3dmodel.model for MakerWorld metadata."""
  271. try:
  272. model_path = "3D/3dmodel.model"
  273. if model_path not in zf.namelist():
  274. return
  275. content = zf.read(model_path).decode("utf-8", errors="ignore")
  276. # Parse XML metadata elements
  277. # MakerWorld adds metadata like: <metadata name="Designer">username</metadata>
  278. metadata_pattern = r'<metadata\s+name="([^"]+)"[^>]*>([^<]*)</metadata>'
  279. matches = re.findall(metadata_pattern, content)
  280. makerworld_fields = {}
  281. for name, value in matches:
  282. makerworld_fields[name] = value.strip()
  283. # Check for direct MakerWorld URL in content
  284. url_pattern = r'https?://makerworld\.com/[^\s<>"\']+/models/(\d+)'
  285. url_match = re.search(url_pattern, content)
  286. if url_match:
  287. self.metadata["makerworld_url"] = url_match.group(0)
  288. self.metadata["makerworld_model_id"] = url_match.group(1)
  289. # Extract model ID from DSM reference in image URLs
  290. # Format: https://makerworld.bblmw.com/makerworld/model/DSM00000001275614/...
  291. # The numeric part (1275614) is the MakerWorld model ID
  292. if "makerworld_url" not in self.metadata:
  293. dsm_pattern = r"DSM0+(\d+)"
  294. dsm_match = re.search(dsm_pattern, content)
  295. if dsm_match:
  296. model_id = dsm_match.group(1)
  297. self.metadata["makerworld_url"] = f"https://makerworld.com/en/models/{model_id}"
  298. self.metadata["makerworld_model_id"] = model_id
  299. # Store designer info
  300. if "Designer" in makerworld_fields:
  301. self.metadata["designer"] = makerworld_fields["Designer"]
  302. if "Title" in makerworld_fields:
  303. self.metadata["print_name"] = makerworld_fields["Title"]
  304. except Exception:
  305. pass # MakerWorld/3dmodel metadata is optional
  306. def _extract_thumbnail(self, zf: zipfile.ZipFile):
  307. """Extract thumbnail image from 3MF.
  308. If a plate_number was specified, try to use that plate's thumbnail first.
  309. """
  310. thumbnail_paths = []
  311. # If a specific plate was printed, try that thumbnail first
  312. if self.plate_number:
  313. thumbnail_paths.append(f"Metadata/plate_{self.plate_number}.png")
  314. # Fallback to default paths
  315. thumbnail_paths.extend(
  316. [
  317. "Metadata/plate_1.png",
  318. "Metadata/thumbnail.png",
  319. "Metadata/model_thumbnail.png",
  320. ]
  321. )
  322. for thumb_path in thumbnail_paths:
  323. if thumb_path in zf.namelist():
  324. self.metadata["_thumbnail_data"] = zf.read(thumb_path)
  325. self.metadata["_thumbnail_ext"] = ".png"
  326. break
  327. def extract_printable_objects_from_3mf(
  328. data: bytes, plate_number: int | None = None, include_positions: bool = False
  329. ) -> dict[int, str] | dict[int, dict] | tuple[dict[int, dict], list | None]:
  330. """Extract printable objects from 3MF file bytes.
  331. This is a lightweight function used during print start to get the list
  332. of objects that can be skipped.
  333. Args:
  334. data: Raw bytes of the 3MF file
  335. plate_number: Which plate was printed (1-based), or None for first plate
  336. include_positions: If True, return tuple of (objects dict, bbox_all)
  337. Returns:
  338. If include_positions=False: Dictionary mapping identify_id (int) to object name (str)
  339. If include_positions=True: Tuple of (dict mapping identify_id to {name, x, y}, bbox_all list or None)
  340. """
  341. from io import BytesIO
  342. printable_objects: dict = {}
  343. bbox_all: list | None = None
  344. try:
  345. with zipfile.ZipFile(BytesIO(data), "r") as zf:
  346. if "Metadata/slice_info.config" not in zf.namelist():
  347. return printable_objects
  348. content = zf.read("Metadata/slice_info.config").decode()
  349. root = ET.fromstring(content)
  350. # Find the correct plate
  351. if plate_number:
  352. plate = root.find(f".//plate[@plate_idx='{plate_number}']")
  353. if plate is None:
  354. plate = root.find(".//plate")
  355. else:
  356. plate = root.find(".//plate")
  357. if plate is None:
  358. return printable_objects
  359. # Get actual plate index from metadata (sliced files only have one plate)
  360. plate_idx = plate_number or 1
  361. for meta in plate.findall("metadata"):
  362. if meta.get("key") == "index":
  363. try:
  364. plate_idx = int(meta.get("value", "1"))
  365. except ValueError:
  366. pass # Use default plate_idx if value is non-numeric
  367. break
  368. # Load position data from plate_N.json if we need positions
  369. # Build a lookup by name - use list to handle duplicate names
  370. bbox_by_name: dict[str, list[list]] = {}
  371. if include_positions:
  372. plate_json_path = f"Metadata/plate_{plate_idx}.json"
  373. if plate_json_path in zf.namelist():
  374. try:
  375. plate_json = json.loads(zf.read(plate_json_path).decode())
  376. # Get bbox_all - the bounding box of all objects (used for image bounds)
  377. bbox_all = plate_json.get("bbox_all")
  378. for bbox_obj in plate_json.get("bbox_objects", []):
  379. obj_name = bbox_obj.get("name")
  380. bbox = bbox_obj.get("bbox", [])
  381. if obj_name and len(bbox) >= 4:
  382. if obj_name not in bbox_by_name:
  383. bbox_by_name[obj_name] = []
  384. bbox_by_name[obj_name].append(bbox)
  385. except (json.JSONDecodeError, KeyError):
  386. pass # Position data is optional; objects will lack x/y coordinates
  387. # Extract objects from slice_info.config
  388. for obj in plate.findall("object"):
  389. identify_id = obj.get("identify_id")
  390. name = obj.get("name")
  391. skipped = obj.get("skipped", "false")
  392. if identify_id and name and skipped.lower() != "true":
  393. try:
  394. obj_id = int(identify_id)
  395. if include_positions:
  396. x, y = None, None
  397. # Match by name - pop first bbox to handle duplicates
  398. bboxes = bbox_by_name.get(name)
  399. if bboxes:
  400. bbox = bboxes.pop(0)
  401. # Calculate center from bbox [x_min, y_min, x_max, y_max]
  402. x = (bbox[0] + bbox[2]) / 2
  403. y = (bbox[1] + bbox[3]) / 2
  404. printable_objects[obj_id] = {"name": name, "x": x, "y": y}
  405. else:
  406. printable_objects[obj_id] = name
  407. except ValueError:
  408. pass # Skip objects with non-numeric identify_id
  409. except Exception:
  410. pass # Return empty dict if 3MF is corrupt or unreadable
  411. if include_positions:
  412. return printable_objects, bbox_all
  413. return printable_objects
  414. class ProjectPageParser:
  415. """Parser for extracting project page data from Bambu Lab 3MF files."""
  416. def __init__(self, file_path: Path):
  417. self.file_path = file_path
  418. def parse(self, archive_id: int) -> dict:
  419. """Extract project page metadata and images from 3MF file."""
  420. import html
  421. result = {
  422. "title": None,
  423. "description": None,
  424. "designer": None,
  425. "designer_user_id": None,
  426. "license": None,
  427. "copyright": None,
  428. "creation_date": None,
  429. "modification_date": None,
  430. "origin": None,
  431. "profile_title": None,
  432. "profile_description": None,
  433. "profile_cover": None,
  434. "profile_user_id": None,
  435. "profile_user_name": None,
  436. "design_model_id": None,
  437. "design_profile_id": None,
  438. "design_region": None,
  439. "model_pictures": [],
  440. "profile_pictures": [],
  441. "thumbnails": [],
  442. }
  443. try:
  444. with zipfile.ZipFile(self.file_path, "r") as zf:
  445. # Parse 3D/3dmodel.model for metadata
  446. model_path = "3D/3dmodel.model"
  447. if model_path in zf.namelist():
  448. content = zf.read(model_path).decode("utf-8", errors="ignore")
  449. # Extract metadata elements using regex
  450. # Format: <metadata name="Key">Value</metadata> or <metadata name="Key" />
  451. metadata_pattern = r'<metadata\s+name="([^"]+)"[^>]*>([^<]*)</metadata>'
  452. matches = re.findall(metadata_pattern, content)
  453. field_mapping = {
  454. "Title": "title",
  455. "Description": "description",
  456. "Designer": "designer",
  457. "DesignerUserId": "designer_user_id",
  458. "License": "license",
  459. "Copyright": "copyright",
  460. "CreationDate": "creation_date",
  461. "ModificationDate": "modification_date",
  462. "Origin": "origin",
  463. "ProfileTitle": "profile_title",
  464. "ProfileDescription": "profile_description",
  465. "ProfileCover": "profile_cover",
  466. "ProfileUserId": "profile_user_id",
  467. "ProfileUserName": "profile_user_name",
  468. "DesignModelId": "design_model_id",
  469. "DesignProfileId": "design_profile_id",
  470. "DesignRegion": "design_region",
  471. }
  472. for name, value in matches:
  473. if name in field_mapping:
  474. # Decode HTML entities multiple times (content is often triple-encoded)
  475. decoded = value.strip()
  476. prev = None
  477. while prev != decoded:
  478. prev = decoded
  479. decoded = html.unescape(decoded)
  480. # Normalize non-breaking spaces to regular spaces
  481. decoded = decoded.replace("\xa0", " ")
  482. result[field_mapping[name]] = decoded if decoded else None
  483. # List images in Auxiliaries folder
  484. from urllib.parse import quote
  485. for name in zf.namelist():
  486. if name.startswith("Auxiliaries/Model Pictures/"):
  487. filename = name.split("/")[-1]
  488. if filename:
  489. result["model_pictures"].append(
  490. {
  491. "name": filename,
  492. "path": name,
  493. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  494. }
  495. )
  496. elif name.startswith("Auxiliaries/Profile Pictures/"):
  497. filename = name.split("/")[-1]
  498. if filename:
  499. result["profile_pictures"].append(
  500. {
  501. "name": filename,
  502. "path": name,
  503. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  504. }
  505. )
  506. elif name.startswith("Auxiliaries/.thumbnails/"):
  507. filename = name.split("/")[-1]
  508. if filename:
  509. result["thumbnails"].append(
  510. {
  511. "name": filename,
  512. "path": name,
  513. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  514. }
  515. )
  516. except Exception as e:
  517. result["_error"] = str(e)
  518. return result
  519. def get_image(self, image_path: str) -> tuple[bytes, str] | None:
  520. """Extract an image from the 3MF file.
  521. Returns tuple of (image_data, content_type) or None if not found.
  522. """
  523. try:
  524. with zipfile.ZipFile(self.file_path, "r") as zf:
  525. if image_path in zf.namelist():
  526. data = zf.read(image_path)
  527. # Determine content type from extension
  528. ext = image_path.lower().split(".")[-1]
  529. content_types = {
  530. "png": "image/png",
  531. "jpg": "image/jpeg",
  532. "jpeg": "image/jpeg",
  533. "webp": "image/webp",
  534. "gif": "image/gif",
  535. }
  536. content_type = content_types.get(ext, "application/octet-stream")
  537. return (data, content_type)
  538. except Exception:
  539. pass # Return None if image cannot be extracted from 3MF
  540. return None
  541. def update_metadata(self, updates: dict) -> bool:
  542. """Update project page metadata in the 3MF file.
  543. Args:
  544. updates: Dict with fields to update (title, description, designer, etc.)
  545. Returns:
  546. True if successful, False otherwise.
  547. """
  548. import html
  549. import tempfile
  550. try:
  551. # Read the 3MF file
  552. with zipfile.ZipFile(self.file_path, "r") as zf_read:
  553. # Find and read the 3dmodel.model file
  554. model_path = "3D/3dmodel.model"
  555. if model_path not in zf_read.namelist():
  556. return False
  557. content = zf_read.read(model_path).decode("utf-8")
  558. # Update metadata fields
  559. field_mapping = {
  560. "title": "Title",
  561. "description": "Description",
  562. "designer": "Designer",
  563. "license": "License",
  564. "copyright": "Copyright",
  565. "profile_title": "ProfileTitle",
  566. "profile_description": "ProfileDescription",
  567. }
  568. for field, xml_name in field_mapping.items():
  569. if field in updates and updates[field] is not None:
  570. new_value = html.escape(updates[field])
  571. # Replace existing metadata or we'd need to add it
  572. pattern = rf'(<metadata\s+name="{xml_name}"[^>]*>)[^<]*(</metadata>)'
  573. replacement = rf"\g<1>{new_value}\g<2>"
  574. content = re.sub(pattern, replacement, content)
  575. # Write to a temporary file first
  576. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf") as tmp:
  577. tmp_path = Path(tmp.name)
  578. # Create new zip with updated content
  579. with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as zf_write:
  580. for item in zf_read.namelist():
  581. if item == model_path:
  582. zf_write.writestr(item, content.encode("utf-8"))
  583. else:
  584. zf_write.writestr(item, zf_read.read(item))
  585. # Replace original file with updated one
  586. shutil.move(tmp_path, self.file_path)
  587. return True
  588. except Exception:
  589. # Clean up temp file if it exists
  590. if "tmp_path" in locals() and tmp_path.exists():
  591. tmp_path.unlink()
  592. return False
  593. class ArchiveService:
  594. """Service for archiving print jobs."""
  595. def __init__(self, db: AsyncSession):
  596. self.db = db
  597. @staticmethod
  598. def compute_file_hash(file_path: Path) -> str:
  599. """Compute SHA256 hash of a file for duplicate detection."""
  600. sha256 = hashlib.sha256()
  601. with open(file_path, "rb") as f:
  602. # Read in chunks to handle large files
  603. for chunk in iter(lambda: f.read(8192), b""):
  604. sha256.update(chunk)
  605. return sha256.hexdigest()
  606. async def get_duplicate_hashes(self) -> set[str]:
  607. """Get all content hashes that appear more than once.
  608. Returns a set of hashes that have duplicates.
  609. """
  610. from sqlalchemy import func
  611. result = await self.db.execute(
  612. select(PrintArchive.content_hash)
  613. .where(PrintArchive.content_hash.isnot(None))
  614. .group_by(PrintArchive.content_hash)
  615. .having(func.count(PrintArchive.id) > 1)
  616. )
  617. return {row[0] for row in result.all()}
  618. async def find_duplicates(
  619. self,
  620. archive_id: int,
  621. content_hash: str | None = None,
  622. print_name: str | None = None,
  623. makerworld_model_id: str | None = None,
  624. ) -> list[dict]:
  625. """Find duplicate archives based on hash or name matching.
  626. Returns list of dicts with id, print_name, created_at, match_type.
  627. """
  628. duplicates = []
  629. # First, find exact matches by content hash
  630. if content_hash:
  631. result = await self.db.execute(
  632. select(PrintArchive)
  633. .where(
  634. and_(
  635. PrintArchive.content_hash == content_hash,
  636. PrintArchive.id != archive_id,
  637. )
  638. )
  639. .order_by(PrintArchive.created_at.desc())
  640. .limit(10)
  641. )
  642. for archive in result.scalars().all():
  643. duplicates.append(
  644. {
  645. "id": archive.id,
  646. "print_name": archive.print_name,
  647. "created_at": archive.created_at,
  648. "match_type": "exact",
  649. }
  650. )
  651. # Then, find similar matches by print name or MakerWorld ID
  652. if print_name or makerworld_model_id:
  653. conditions = [PrintArchive.id != archive_id]
  654. name_conditions = []
  655. if print_name:
  656. # Match if print names are similar (ignoring case)
  657. name_conditions.append(PrintArchive.print_name.ilike(print_name))
  658. if makerworld_model_id:
  659. # Match by MakerWorld model ID stored in extra_data
  660. # Use json_extract for SQLite compatibility (astext is PostgreSQL-only)
  661. from sqlalchemy import func
  662. name_conditions.append(
  663. func.json_extract(PrintArchive.extra_data, "$.makerworld_model_id") == str(makerworld_model_id)
  664. )
  665. if name_conditions:
  666. conditions.append(or_(*name_conditions))
  667. result = await self.db.execute(
  668. select(PrintArchive).where(and_(*conditions)).order_by(PrintArchive.created_at.desc()).limit(10)
  669. )
  670. for archive in result.scalars().all():
  671. # Don't add if already in duplicates (exact match)
  672. if not any(d["id"] == archive.id for d in duplicates):
  673. duplicates.append(
  674. {
  675. "id": archive.id,
  676. "print_name": archive.print_name,
  677. "created_at": archive.created_at,
  678. "match_type": "similar",
  679. }
  680. )
  681. return duplicates
  682. async def archive_print(
  683. self,
  684. printer_id: int | None,
  685. source_file: Path,
  686. print_data: dict | None = None,
  687. created_by_id: int | None = None,
  688. ) -> PrintArchive | None:
  689. """Archive a 3MF file with metadata.
  690. Args:
  691. printer_id: ID of the printer (optional)
  692. source_file: Path to the 3MF file
  693. print_data: Print data from MQTT (optional)
  694. created_by_id: User ID who created this archive (optional, for user tracking)
  695. """
  696. # Verify printer exists if specified
  697. if printer_id is not None:
  698. result = await self.db.execute(select(Printer).where(Printer.id == printer_id))
  699. printer = result.scalar_one_or_none()
  700. if not printer:
  701. return None
  702. # Create archive directory structure
  703. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  704. archive_name = f"{timestamp}_{source_file.stem}"
  705. # Use "unassigned" folder for archives without a printer
  706. printer_folder = str(printer_id) if printer_id is not None else "unassigned"
  707. archive_dir = settings.archive_dir / printer_folder / archive_name
  708. archive_dir.mkdir(parents=True, exist_ok=True)
  709. # Copy 3MF file
  710. dest_file = archive_dir / source_file.name
  711. shutil.copy2(source_file, dest_file)
  712. # Compute content hash for duplicate detection
  713. content_hash = self.compute_file_hash(dest_file)
  714. # Extract plate number from filename (e.g., "plate_5" from "/data/Metadata/plate_5.gcode")
  715. plate_number = None
  716. if print_data:
  717. filename = print_data.get("filename", "")
  718. match = re.search(r"plate_(\d+)", filename)
  719. if match:
  720. plate_number = int(match.group(1))
  721. # Parse 3MF metadata
  722. parser = ThreeMFParser(dest_file, plate_number=plate_number)
  723. metadata = parser.parse()
  724. # Save thumbnail if present
  725. thumbnail_path = None
  726. if "_thumbnail_data" in metadata:
  727. thumb_file = archive_dir / f"thumbnail{metadata['_thumbnail_ext']}"
  728. thumb_file.write_bytes(metadata["_thumbnail_data"])
  729. thumbnail_path = str(thumb_file.relative_to(settings.base_dir))
  730. del metadata["_thumbnail_data"]
  731. del metadata["_thumbnail_ext"]
  732. # Merge with print data from MQTT
  733. if print_data:
  734. metadata["_print_data"] = print_data
  735. # Determine status and timestamps
  736. status = print_data.get("status", "completed") if print_data else "archived"
  737. started_at = datetime.now() if status == "printing" else None
  738. completed_at = datetime.now() if status in ("completed", "failed", "archived") else None
  739. # Calculate cost based on filament usage and type
  740. cost = None
  741. filament_grams = metadata.get("filament_used_grams")
  742. filament_type = metadata.get("filament_type")
  743. if filament_grams and filament_type:
  744. # For multi-material prints, use the first filament type for cost calculation
  745. primary_type = filament_type.split(",")[0].strip()
  746. # Look up filament cost_per_kg from database
  747. filament_result = await self.db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  748. filament = filament_result.scalar_one_or_none()
  749. if filament:
  750. cost = round((filament_grams / 1000) * filament.cost_per_kg, 2)
  751. else:
  752. # Use default filament cost from settings
  753. from backend.app.api.routes.settings import get_setting
  754. default_cost_setting = await get_setting(self.db, "default_filament_cost")
  755. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  756. cost = round((filament_grams / 1000) * default_cost_per_kg, 2)
  757. # Calculate quantity from printable objects count
  758. # printable_objects is a dict of {identify_id: name} for non-skipped objects
  759. quantity = 1 # Default to 1
  760. printable_objects = metadata.get("printable_objects")
  761. if printable_objects and isinstance(printable_objects, dict):
  762. quantity = len(printable_objects)
  763. logger.debug("Auto-detected %s parts from 3MF printable objects", quantity)
  764. # Create archive record
  765. archive = PrintArchive(
  766. printer_id=printer_id,
  767. filename=source_file.name,
  768. file_path=str(dest_file.relative_to(settings.base_dir)),
  769. file_size=dest_file.stat().st_size,
  770. content_hash=content_hash,
  771. thumbnail_path=thumbnail_path,
  772. print_name=metadata.get("print_name") or source_file.stem,
  773. print_time_seconds=metadata.get("print_time_seconds"),
  774. filament_used_grams=metadata.get("filament_used_grams"),
  775. filament_type=metadata.get("filament_type"),
  776. filament_color=metadata.get("filament_color"),
  777. layer_height=metadata.get("layer_height"),
  778. total_layers=metadata.get("total_layers"),
  779. nozzle_diameter=metadata.get("nozzle_diameter"),
  780. bed_temperature=metadata.get("bed_temperature"),
  781. nozzle_temperature=metadata.get("nozzle_temperature"),
  782. sliced_for_model=metadata.get("sliced_for_model"),
  783. makerworld_url=metadata.get("makerworld_url"),
  784. designer=metadata.get("designer"),
  785. status=status,
  786. started_at=started_at,
  787. completed_at=completed_at,
  788. cost=cost,
  789. quantity=quantity,
  790. extra_data=metadata,
  791. created_by_id=created_by_id,
  792. )
  793. self.db.add(archive)
  794. await self.db.commit()
  795. await self.db.refresh(archive)
  796. return archive
  797. async def get_archive(self, archive_id: int) -> PrintArchive | None:
  798. """Get an archive by ID with relationships loaded."""
  799. from sqlalchemy.orm import selectinload
  800. result = await self.db.execute(
  801. select(PrintArchive)
  802. .options(selectinload(PrintArchive.created_by), selectinload(PrintArchive.project))
  803. .where(PrintArchive.id == archive_id)
  804. )
  805. return result.scalar_one_or_none()
  806. async def update_archive_status(
  807. self,
  808. archive_id: int,
  809. status: str,
  810. completed_at: datetime | None = None,
  811. failure_reason: str | None = None,
  812. ) -> bool:
  813. """Update the status of an archive."""
  814. archive = await self.get_archive(archive_id)
  815. if not archive:
  816. return False
  817. archive.status = status
  818. if completed_at:
  819. archive.completed_at = completed_at
  820. if failure_reason:
  821. archive.failure_reason = failure_reason
  822. await self.db.commit()
  823. return True
  824. async def add_reprint_cost(self, archive_id: int) -> bool:
  825. """Add cost for a reprint to the existing archive cost."""
  826. archive = await self.get_archive(archive_id)
  827. if not archive:
  828. return False
  829. if not archive.filament_used_grams or not archive.filament_type:
  830. return False
  831. # Calculate cost based on filament type or default
  832. from backend.app.api.routes.settings import get_setting
  833. primary_type = archive.filament_type.split(",")[0].strip()
  834. # Look up filament cost_per_kg from database
  835. filament_result = await self.db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  836. filament = filament_result.scalar_one_or_none()
  837. if filament:
  838. cost_per_kg = filament.cost_per_kg
  839. else:
  840. # Use default filament cost from settings
  841. default_cost_setting = await get_setting(self.db, "default_filament_cost")
  842. cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  843. additional_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  844. # Add to existing cost (or set if None)
  845. if archive.cost is None:
  846. archive.cost = additional_cost
  847. else:
  848. archive.cost = round(archive.cost + additional_cost, 2)
  849. await self.db.commit()
  850. logger.info("Added reprint cost %s to archive %s, new total: %s", additional_cost, archive_id, archive.cost)
  851. return True
  852. async def list_archives(
  853. self,
  854. printer_id: int | None = None,
  855. project_id: int | None = None,
  856. limit: int = 50,
  857. offset: int = 0,
  858. ) -> list[PrintArchive]:
  859. """List archives with optional filtering."""
  860. from sqlalchemy.orm import selectinload
  861. query = (
  862. select(PrintArchive)
  863. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  864. .order_by(PrintArchive.created_at.desc())
  865. )
  866. if printer_id:
  867. query = query.where(PrintArchive.printer_id == printer_id)
  868. if project_id:
  869. query = query.where(PrintArchive.project_id == project_id)
  870. query = query.limit(limit).offset(offset)
  871. result = await self.db.execute(query)
  872. return list(result.scalars().all())
  873. async def delete_archive(self, archive_id: int) -> bool:
  874. """Delete an archive and its files."""
  875. archive = await self.get_archive(archive_id)
  876. if not archive:
  877. return False
  878. # Resolve the directory to delete BEFORE committing the DB change
  879. dir_to_delete: Path | None = None
  880. if archive.file_path and archive.file_path.strip():
  881. file_path = settings.base_dir / archive.file_path
  882. if file_path.exists():
  883. archive_dir = file_path.parent
  884. # Safety check 1: archive_dir must be inside archive_dir
  885. try:
  886. archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  887. except ValueError:
  888. logger.error(
  889. f"SECURITY: Refusing to delete archive {archive_id} - "
  890. f"path {archive_dir} is outside archive directory {settings.archive_dir}"
  891. )
  892. await self.db.delete(archive)
  893. await self.db.commit()
  894. return True
  895. # Safety check 2: archive_dir must be at least 1 level deep inside archive_dir
  896. try:
  897. relative_path = archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  898. if len(relative_path.parts) < 1:
  899. logger.error(
  900. f"SECURITY: Refusing to delete archive {archive_id} - "
  901. f"path {archive_dir} is not deep enough inside archive directory"
  902. )
  903. await self.db.delete(archive)
  904. await self.db.commit()
  905. return True
  906. except ValueError:
  907. pass # Already handled above
  908. dir_to_delete = archive_dir
  909. else:
  910. logger.error(
  911. f"SECURITY: Refusing to delete files for archive {archive_id} - "
  912. f"file_path is empty or invalid: '{archive.file_path}'"
  913. )
  914. # Delete database record FIRST — if the commit fails (e.g. database locked
  915. # during concurrent bulk deletes), the files stay on disk and nothing is lost.
  916. await self.db.delete(archive)
  917. await self.db.commit()
  918. # Only delete files AFTER the DB commit succeeds to avoid orphaned records
  919. if dir_to_delete:
  920. shutil.rmtree(dir_to_delete, ignore_errors=True)
  921. return True
  922. async def attach_timelapse(
  923. self,
  924. archive_id: int,
  925. timelapse_data: bytes,
  926. filename: str = "timelapse.mp4",
  927. ) -> bool:
  928. """Attach a timelapse video to an archive."""
  929. import asyncio
  930. archive = await self.get_archive(archive_id)
  931. if not archive:
  932. return False
  933. # Get archive directory
  934. file_path = settings.base_dir / archive.file_path
  935. archive_dir = file_path.parent
  936. # Save timelapse - use thread pool to avoid blocking event loop
  937. # (timelapse files can be 100MB+, sync write blocks for seconds)
  938. timelapse_file = archive_dir / filename
  939. await asyncio.to_thread(timelapse_file.write_bytes, timelapse_data)
  940. # Update archive record
  941. archive.timelapse_path = str(timelapse_file.relative_to(settings.base_dir))
  942. await self.db.commit()
  943. return True