archive.py 37 KB

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