archive.py 33 KB

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