archive.py 31 KB

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