archive.py 42 KB

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