archive.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. import hashlib
  2. import json
  3. import logging
  4. import os
  5. import re
  6. import shutil
  7. import zipfile
  8. from datetime import date, datetime, time, timezone
  9. from pathlib import Path
  10. from defusedxml import ElementTree as ET
  11. from sqlalchemy import and_, or_, select, text
  12. from sqlalchemy.ext.asyncio import AsyncSession
  13. from backend.app.core.config import settings
  14. from backend.app.models.archive import PrintArchive
  15. from backend.app.models.filament import Filament
  16. from backend.app.models.printer import Printer
  17. logger = logging.getLogger(__name__)
  18. def _copy_and_fsync(src: Path, dst: Path, chunk_size: int = 1024 * 1024) -> None:
  19. """Copy src to dst with an explicit chunked read/write and fsync the dst.
  20. Replacement for shutil.copy2 in the archive pipeline. shutil.copy2 uses
  21. Linux sendfile(), which on some kernels/filesystems has returned a short
  22. count on the first call and truncated the destination for larger 3MF
  23. uploads (#1032, observed on Raspberry Pi OS bookworm / armv7l). An
  24. explicit loop with fsync avoids that path and guarantees the dest bytes
  25. are on disk before the caller inspects them as a ZIP.
  26. """
  27. with src.open("rb") as rf, dst.open("wb") as wf:
  28. while True:
  29. buf = rf.read(chunk_size)
  30. if not buf:
  31. break
  32. wf.write(buf)
  33. wf.flush()
  34. os.fsync(wf.fileno())
  35. shutil.copystat(src, dst)
  36. def resolve_display_stem(filename: str) -> str:
  37. """Return a clean human-readable stem from a 3MF/gcode filename.
  38. Bambu Studio's "Send to printer" dialog typically writes files like
  39. ``Plate_1.gcode.3mf`` (a sliced gcode payload wrapped in a 3MF container).
  40. The naive ``Path(filename).stem`` only drops the last suffix, leaving
  41. ``Plate_1.gcode`` — which then surfaces in the archive UI as a confusing
  42. ``Plate_1.gcode`` rather than ``Plate_1`` (#1152 follow-up).
  43. Strip the recognised print-format suffixes in order:
  44. - ``.gcode.3mf`` → bare stem (Bambu Studio FTP send)
  45. - ``.3mf`` → bare stem
  46. - ``.gcode`` → bare stem (rare standalone gcode upload)
  47. Anything else passes through unchanged.
  48. """
  49. name = Path(filename).name # drop any path components
  50. lower = name.lower()
  51. for suffix in (".gcode.3mf", ".3mf", ".gcode"):
  52. if lower.endswith(suffix):
  53. return name[: -len(suffix)]
  54. return Path(name).stem
  55. class ThreeMFParser:
  56. """Parser for Bambu Lab 3MF files."""
  57. def __init__(self, file_path: Path, plate_number: int | None = None):
  58. self.file_path = file_path
  59. self.plate_number = plate_number # Which plate was printed (1, 2, 3, etc.)
  60. self.metadata: dict = {}
  61. def parse(self) -> dict:
  62. """Extract metadata from 3MF file."""
  63. try:
  64. with zipfile.ZipFile(self.file_path, "r") as zf:
  65. self._parse_slice_info(zf) # Now sets self.plate_number from slice_info
  66. self._parse_project_settings(zf)
  67. self._parse_gcode_header(zf)
  68. self._parse_3dmodel(zf)
  69. self._extract_thumbnail(zf) # Uses correct plate_number for thumbnail
  70. # Enhance print_name with plate info if this is a multi-plate export
  71. plate_index = self.metadata.get("_plate_index")
  72. if plate_index and plate_index > 1:
  73. # Append plate number to distinguish from other plates
  74. existing_name = self.metadata.get("print_name", "")
  75. if existing_name and f"Plate {plate_index}" not in existing_name:
  76. self.metadata["print_name"] = f"{existing_name} - Plate {plate_index}"
  77. # ALWAYS prefer slice_info values - they contain ONLY filaments actually used in print
  78. # project_settings contains ALL configured filaments (AMS slots), not just used ones
  79. if self.metadata.get("_slice_filament_type"):
  80. self.metadata["filament_type"] = self.metadata["_slice_filament_type"]
  81. if self.metadata.get("_slice_filament_color"):
  82. self.metadata["filament_color"] = self.metadata["_slice_filament_color"]
  83. # Clean up internal keys
  84. self.metadata.pop("_slice_filament_type", None)
  85. self.metadata.pop("_slice_filament_color", None)
  86. self.metadata.pop("_plate_index", None)
  87. except Exception as e:
  88. # Return whatever metadata was extracted before the error, but
  89. # surface the failure so corrupted / truncated 3MF archives are
  90. # visible in support bundles (#1032).
  91. logger.warning(
  92. "ThreeMFParser: failed to parse %s: %s(%s) — returning partial metadata",
  93. self.file_path,
  94. type(e).__name__,
  95. e,
  96. )
  97. return self.metadata
  98. def _parse_slice_info(self, zf: zipfile.ZipFile):
  99. """Parse slice_info.config for print settings and printable objects."""
  100. try:
  101. if "Metadata/slice_info.config" in zf.namelist():
  102. content = zf.read("Metadata/slice_info.config").decode()
  103. root = ET.fromstring(content)
  104. # Extract printer_model_id from plate metadata
  105. # Format: <plate><metadata key="printer_model_id" value="C11" /></plate>
  106. for meta in root.findall(".//metadata"):
  107. key = meta.get("key")
  108. value = meta.get("value")
  109. if key == "printer_model_id" and value:
  110. from backend.app.utils.printer_models import normalize_printer_model_id
  111. normalized = normalize_printer_model_id(value)
  112. if normalized:
  113. self.metadata["sliced_for_model"] = normalized
  114. break
  115. # Find the plate element (single-plate exports only have one plate)
  116. plate = root.find(".//plate")
  117. if plate is not None:
  118. # Extract metadata from plate element
  119. for meta in plate.findall("metadata"):
  120. key = meta.get("key")
  121. value = meta.get("value")
  122. if key == "index" and value:
  123. # Extract plate index - this tells us which plate was exported
  124. try:
  125. extracted_index = int(value)
  126. # Set plate_number if not already set from filename
  127. if not self.plate_number:
  128. self.plate_number = extracted_index
  129. # Store in metadata for print_name generation
  130. self.metadata["_plate_index"] = extracted_index
  131. except ValueError:
  132. pass # Skip non-numeric plate index
  133. elif key == "prediction" and value:
  134. self.metadata["print_time_seconds"] = int(value)
  135. elif key == "weight" and value:
  136. self.metadata["filament_used_grams"] = float(value)
  137. # Extract printable objects for skip object functionality
  138. # Objects are stored as <object identify_id="123" name="Part1" skipped="false" />
  139. printable_objects = {}
  140. for obj in plate.findall("object"):
  141. identify_id = obj.get("identify_id")
  142. name = obj.get("name")
  143. skipped = obj.get("skipped", "false")
  144. # Only include objects that are not pre-skipped
  145. if identify_id and name and skipped.lower() != "true":
  146. try:
  147. printable_objects[int(identify_id)] = name
  148. except ValueError:
  149. pass # Skip objects with non-numeric identify_id
  150. if printable_objects:
  151. self.metadata["printable_objects"] = printable_objects
  152. # Get filament info from filaments ACTUALLY USED in the print
  153. # slice_info has <filament id="1" type="PLA" color="#FFFFFF" used_g="100" />
  154. # Only include filaments where used_g > 0
  155. filaments = root.findall(".//filament")
  156. if filaments:
  157. # Collect unique filament types and colors for filaments that are actually used
  158. types = []
  159. colors = []
  160. for f in filaments:
  161. # Check if this filament is actually used in the print
  162. used_g = f.get("used_g", "0")
  163. try:
  164. used_amount = float(used_g)
  165. except (ValueError, TypeError):
  166. used_amount = 0
  167. # Only include if used_g > 0 (filament is actually consumed)
  168. if used_amount > 0:
  169. ftype = f.get("type")
  170. fcolor = f.get("color")
  171. if ftype and ftype not in types:
  172. types.append(ftype)
  173. if fcolor and fcolor not in colors:
  174. colors.append(fcolor)
  175. if types:
  176. self.metadata["_slice_filament_type"] = ", ".join(types)
  177. if colors:
  178. self.metadata["_slice_filament_color"] = ",".join(colors)
  179. # Collect per-slot filament usage for tracking & notifications
  180. filament_slots = []
  181. for f in filaments:
  182. slot_id = f.get("id")
  183. used_g_str = f.get("used_g", "0")
  184. try:
  185. used_g = float(used_g_str)
  186. except (ValueError, TypeError):
  187. used_g = 0
  188. if used_g > 0 and slot_id:
  189. filament_slots.append(
  190. {
  191. "slot_id": int(slot_id),
  192. "used_g": round(used_g, 2),
  193. "type": f.get("type", ""),
  194. "color": f.get("color", ""),
  195. }
  196. )
  197. if filament_slots:
  198. self.metadata["filament_slots"] = filament_slots
  199. except Exception:
  200. pass # Skip unparseable slice_info metadata
  201. def _parse_project_settings(self, zf: zipfile.ZipFile):
  202. """Parse project settings for print configuration."""
  203. try:
  204. if "Metadata/project_settings.config" in zf.namelist():
  205. content = zf.read("Metadata/project_settings.config").decode()
  206. try:
  207. data = json.loads(content)
  208. self._extract_filament_info(data)
  209. self._extract_print_settings(data)
  210. except json.JSONDecodeError:
  211. pass # Skip malformed project_settings JSON
  212. except Exception:
  213. pass # Skip unreadable project settings file
  214. def _parse_gcode_header(self, zf: zipfile.ZipFile):
  215. """Parse G-code file header for total layer count and printer model."""
  216. try:
  217. # Look for plate_1.gcode or similar
  218. gcode_files = [f for f in zf.namelist() if f.endswith(".gcode")]
  219. if not gcode_files:
  220. return
  221. # Read first 4KB of G-code (header contains metadata)
  222. gcode_path = gcode_files[0]
  223. with zf.open(gcode_path) as f:
  224. header = f.read(4096).decode("utf-8", errors="ignore")
  225. # Look for "; total layer number: XX" pattern
  226. match = re.search(r";\s*total\s+layer\s+number[:\s]+(\d+)", header, re.IGNORECASE)
  227. if match:
  228. self.metadata["total_layers"] = int(match.group(1))
  229. # Look for printer_model in gcode header (fallback if not found in slice_info)
  230. # Format: "; printer_model = Bambu Lab X1 Carbon" or "; printer_model = X1C"
  231. if "sliced_for_model" not in self.metadata:
  232. match = re.search(r";\s*printer_model\s*=\s*(.+)", header, re.IGNORECASE)
  233. if match:
  234. from backend.app.utils.printer_models import normalize_printer_model
  235. raw_model = match.group(1).strip()
  236. self.metadata["sliced_for_model"] = normalize_printer_model(raw_model)
  237. except Exception:
  238. pass # G-code header parsing is best-effort; metadata may come from other sources
  239. def _extract_filament_info(self, data: dict):
  240. """Extract filament info, preferring non-support filaments."""
  241. try:
  242. filament_types = data.get("filament_type", [])
  243. filament_colors = data.get("filament_colour", [])
  244. filament_is_support = data.get("filament_is_support", [])
  245. if not filament_types:
  246. return
  247. # Collect all non-support filaments
  248. non_support_types = []
  249. non_support_colors = []
  250. for i, ftype in enumerate(filament_types):
  251. is_support = filament_is_support[i] if i < len(filament_is_support) else "0"
  252. if is_support == "0":
  253. if ftype and ftype not in non_support_types:
  254. non_support_types.append(ftype)
  255. if i < len(filament_colors) and filament_colors[i]:
  256. color = filament_colors[i]
  257. if color not in non_support_colors:
  258. non_support_colors.append(color)
  259. # Fallback to first filament if all are support
  260. if not non_support_types and filament_types:
  261. non_support_types = [filament_types[0]]
  262. if not non_support_colors and filament_colors:
  263. non_support_colors = [filament_colors[0]]
  264. # Store filament type(s)
  265. if non_support_types:
  266. self.metadata["filament_type"] = ", ".join(non_support_types)
  267. # Store all colors as comma-separated (for multi-color display)
  268. if non_support_colors:
  269. self.metadata["filament_color"] = ",".join(non_support_colors)
  270. except Exception:
  271. pass # Filament info is optional; fall back to slice_info values
  272. def _extract_print_settings(self, data: dict):
  273. """Extract print settings from JSON config."""
  274. try:
  275. # Layer height - usually an array, get first value
  276. if "layer_height" in data:
  277. val = data["layer_height"]
  278. if isinstance(val, list) and val:
  279. self.metadata["layer_height"] = float(val[0])
  280. elif isinstance(val, (int, float, str)):
  281. self.metadata["layer_height"] = float(val)
  282. # Nozzle diameter
  283. if "nozzle_diameter" in data:
  284. val = data["nozzle_diameter"]
  285. if isinstance(val, list) and val:
  286. self.metadata["nozzle_diameter"] = float(val[0])
  287. elif isinstance(val, (int, float, str)):
  288. self.metadata["nozzle_diameter"] = float(val)
  289. # Bed temperature - first layer or regular
  290. for key in ["bed_temperature_initial_layer", "bed_temperature"]:
  291. if key in data:
  292. val = data[key]
  293. if isinstance(val, list) and val:
  294. self.metadata["bed_temperature"] = int(float(val[0]))
  295. elif isinstance(val, (int, float, str)):
  296. self.metadata["bed_temperature"] = int(float(val))
  297. break
  298. # Nozzle temperature
  299. for key in ["nozzle_temperature_initial_layer", "nozzle_temperature"]:
  300. if key in data:
  301. val = data[key]
  302. if isinstance(val, list) and val:
  303. self.metadata["nozzle_temperature"] = int(float(val[0]))
  304. elif isinstance(val, (int, float, str)):
  305. self.metadata["nozzle_temperature"] = int(float(val))
  306. break
  307. # Printer model (extract and normalize)
  308. if "printer_model" in data:
  309. from backend.app.utils.printer_models import normalize_printer_model
  310. self.metadata["sliced_for_model"] = normalize_printer_model(data["printer_model"])
  311. except Exception:
  312. pass # Print settings are optional; missing values are left unset
  313. def _extract_settings_from_content(self, content: str):
  314. """Extract print settings from config content."""
  315. settings_map = {
  316. "layer_height": ("layer_height", float),
  317. "nozzle_diameter": ("nozzle_diameter", float),
  318. "bed_temperature": ("bed_temperature", int),
  319. "nozzle_temperature": ("nozzle_temperature", int),
  320. }
  321. for key, (search_key, converter) in settings_map.items():
  322. if key not in self.metadata:
  323. try:
  324. # Try JSON format
  325. if f'"{search_key}"' in content:
  326. start = content.find(f'"{search_key}"')
  327. value_start = content.find(":", start) + 1
  328. value_end = content.find(",", value_start)
  329. if value_end == -1:
  330. value_end = content.find("}", value_start)
  331. value = content[value_start:value_end].strip().strip('"')
  332. self.metadata[key] = converter(value)
  333. except (ValueError, TypeError):
  334. pass # Skip settings with unconvertible values
  335. def _parse_3dmodel(self, zf: zipfile.ZipFile):
  336. """Parse 3D/3dmodel.model for MakerWorld metadata."""
  337. try:
  338. model_path = "3D/3dmodel.model"
  339. if model_path not in zf.namelist():
  340. return
  341. content = zf.read(model_path).decode("utf-8", errors="ignore")
  342. # Parse XML metadata elements
  343. # MakerWorld adds metadata like: <metadata name="Designer">username</metadata>
  344. metadata_pattern = r'<metadata\s+name="([^"]+)"[^>]*>([^<]*)</metadata>'
  345. matches = re.findall(metadata_pattern, content)
  346. makerworld_fields = {}
  347. for name, value in matches:
  348. makerworld_fields[name] = value.strip()
  349. # Check for direct MakerWorld URL in content
  350. url_pattern = r'https?://makerworld\.com/[^\s<>"\']+/models/(\d+)'
  351. url_match = re.search(url_pattern, content)
  352. if url_match:
  353. self.metadata["makerworld_url"] = url_match.group(0)
  354. self.metadata["makerworld_model_id"] = url_match.group(1)
  355. # Extract model ID from DSM reference in image URLs
  356. # Format: https://makerworld.bblmw.com/makerworld/model/DSM00000001275614/...
  357. # The numeric part (1275614) is the MakerWorld model ID
  358. if "makerworld_url" not in self.metadata:
  359. dsm_pattern = r"DSM0+(\d+)"
  360. dsm_match = re.search(dsm_pattern, content)
  361. if dsm_match:
  362. model_id = dsm_match.group(1)
  363. self.metadata["makerworld_url"] = f"https://makerworld.com/en/models/{model_id}"
  364. self.metadata["makerworld_model_id"] = model_id
  365. # Store designer info
  366. if "Designer" in makerworld_fields:
  367. self.metadata["designer"] = makerworld_fields["Designer"]
  368. if "Title" in makerworld_fields:
  369. self.metadata["print_name"] = makerworld_fields["Title"]
  370. except Exception:
  371. pass # MakerWorld/3dmodel metadata is optional
  372. def _extract_thumbnail(self, zf: zipfile.ZipFile):
  373. """Extract thumbnail image from 3MF.
  374. If a plate_number was specified, try to use that plate's thumbnail first.
  375. """
  376. thumbnail_paths = []
  377. # If a specific plate was printed, try that thumbnail first
  378. if self.plate_number:
  379. thumbnail_paths.append(f"Metadata/plate_{self.plate_number}.png")
  380. # Fallback to default paths
  381. thumbnail_paths.extend(
  382. [
  383. "Metadata/plate_1.png",
  384. "Metadata/thumbnail.png",
  385. "Metadata/model_thumbnail.png",
  386. ]
  387. )
  388. for thumb_path in thumbnail_paths:
  389. if thumb_path in zf.namelist():
  390. self.metadata["_thumbnail_data"] = zf.read(thumb_path)
  391. self.metadata["_thumbnail_ext"] = ".png"
  392. break
  393. def extract_printable_objects_from_3mf(
  394. data: bytes, plate_number: int | None = None, include_positions: bool = False
  395. ) -> dict[int, str] | dict[int, dict] | tuple[dict[int, dict], list | None]:
  396. """Extract printable objects from 3MF file bytes.
  397. This is a lightweight function used during print start to get the list
  398. of objects that can be skipped.
  399. Args:
  400. data: Raw bytes of the 3MF file
  401. plate_number: Which plate was printed (1-based), or None for first plate
  402. include_positions: If True, return tuple of (objects dict, bbox_all)
  403. Returns:
  404. If include_positions=False: Dictionary mapping identify_id (int) to object name (str)
  405. If include_positions=True: Tuple of (dict mapping identify_id to {name, x, y}, bbox_all list or None)
  406. """
  407. from io import BytesIO
  408. printable_objects: dict = {}
  409. bbox_all: list | None = None
  410. try:
  411. with zipfile.ZipFile(BytesIO(data), "r") as zf:
  412. if "Metadata/slice_info.config" not in zf.namelist():
  413. return printable_objects
  414. content = zf.read("Metadata/slice_info.config").decode()
  415. root = ET.fromstring(content)
  416. # Find the correct plate
  417. if plate_number:
  418. plate = root.find(f".//plate[@plate_idx='{plate_number}']")
  419. if plate is None:
  420. plate = root.find(".//plate")
  421. else:
  422. plate = root.find(".//plate")
  423. if plate is None:
  424. return printable_objects
  425. # Get actual plate index from metadata (sliced files only have one plate)
  426. plate_idx = plate_number or 1
  427. for meta in plate.findall("metadata"):
  428. if meta.get("key") == "index":
  429. try:
  430. plate_idx = int(meta.get("value", "1"))
  431. except ValueError:
  432. pass # Use default plate_idx if value is non-numeric
  433. break
  434. # Load position data from plate_N.json if we need positions
  435. # Build a lookup by name - use list to handle duplicate names
  436. bbox_by_name: dict[str, list[list]] = {}
  437. if include_positions:
  438. plate_json_path = f"Metadata/plate_{plate_idx}.json"
  439. if plate_json_path in zf.namelist():
  440. try:
  441. plate_json = json.loads(zf.read(plate_json_path).decode())
  442. # Get bbox_all - the bounding box of all objects (used for image bounds)
  443. bbox_all = plate_json.get("bbox_all")
  444. for bbox_obj in plate_json.get("bbox_objects", []):
  445. obj_name = bbox_obj.get("name")
  446. bbox = bbox_obj.get("bbox", [])
  447. if obj_name and len(bbox) >= 4:
  448. if obj_name not in bbox_by_name:
  449. bbox_by_name[obj_name] = []
  450. bbox_by_name[obj_name].append(bbox)
  451. except (json.JSONDecodeError, KeyError):
  452. pass # Position data is optional; objects will lack x/y coordinates
  453. # Extract objects from slice_info.config
  454. for obj in plate.findall("object"):
  455. identify_id = obj.get("identify_id")
  456. name = obj.get("name")
  457. skipped = obj.get("skipped", "false")
  458. if identify_id and name and skipped.lower() != "true":
  459. try:
  460. obj_id = int(identify_id)
  461. if include_positions:
  462. x, y = None, None
  463. # Match by name - pop first bbox to handle duplicates
  464. bboxes = bbox_by_name.get(name)
  465. if bboxes:
  466. bbox = bboxes.pop(0)
  467. # Calculate center from bbox [x_min, y_min, x_max, y_max]
  468. x = (bbox[0] + bbox[2]) / 2
  469. y = (bbox[1] + bbox[3]) / 2
  470. printable_objects[obj_id] = {"name": name, "x": x, "y": y}
  471. else:
  472. printable_objects[obj_id] = name
  473. except ValueError:
  474. pass # Skip objects with non-numeric identify_id
  475. except Exception:
  476. pass # Return empty dict if 3MF is corrupt or unreadable
  477. if include_positions:
  478. return printable_objects, bbox_all
  479. return printable_objects
  480. class ProjectPageParser:
  481. """Parser for extracting project page data from Bambu Lab 3MF files."""
  482. def __init__(self, file_path: Path):
  483. self.file_path = file_path
  484. def parse(self, archive_id: int) -> dict:
  485. """Extract project page metadata and images from 3MF file."""
  486. import html
  487. result = {
  488. "title": None,
  489. "description": None,
  490. "designer": None,
  491. "designer_user_id": None,
  492. "license": None,
  493. "copyright": None,
  494. "creation_date": None,
  495. "modification_date": None,
  496. "origin": None,
  497. "profile_title": None,
  498. "profile_description": None,
  499. "profile_cover": None,
  500. "profile_user_id": None,
  501. "profile_user_name": None,
  502. "design_model_id": None,
  503. "design_profile_id": None,
  504. "design_region": None,
  505. "model_pictures": [],
  506. "profile_pictures": [],
  507. "thumbnails": [],
  508. }
  509. try:
  510. with zipfile.ZipFile(self.file_path, "r") as zf:
  511. # Parse 3D/3dmodel.model for metadata
  512. model_path = "3D/3dmodel.model"
  513. if model_path in zf.namelist():
  514. content = zf.read(model_path).decode("utf-8", errors="ignore")
  515. # Extract metadata elements using regex
  516. # Format: <metadata name="Key">Value</metadata> or <metadata name="Key" />
  517. metadata_pattern = r'<metadata\s+name="([^"]+)"[^>]*>([^<]*)</metadata>'
  518. matches = re.findall(metadata_pattern, content)
  519. field_mapping = {
  520. "Title": "title",
  521. "Description": "description",
  522. "Designer": "designer",
  523. "DesignerUserId": "designer_user_id",
  524. "License": "license",
  525. "Copyright": "copyright",
  526. "CreationDate": "creation_date",
  527. "ModificationDate": "modification_date",
  528. "Origin": "origin",
  529. "ProfileTitle": "profile_title",
  530. "ProfileDescription": "profile_description",
  531. "ProfileCover": "profile_cover",
  532. "ProfileUserId": "profile_user_id",
  533. "ProfileUserName": "profile_user_name",
  534. "DesignModelId": "design_model_id",
  535. "DesignProfileId": "design_profile_id",
  536. "DesignRegion": "design_region",
  537. }
  538. for name, value in matches:
  539. if name in field_mapping:
  540. # Decode HTML entities multiple times (content is often triple-encoded)
  541. decoded = value.strip()
  542. prev = None
  543. while prev != decoded:
  544. prev = decoded
  545. decoded = html.unescape(decoded)
  546. # Normalize non-breaking spaces to regular spaces
  547. decoded = decoded.replace("\xa0", " ")
  548. result[field_mapping[name]] = decoded if decoded else None
  549. # List images in Auxiliaries folder
  550. from urllib.parse import quote
  551. for name in zf.namelist():
  552. if name.startswith("Auxiliaries/Model Pictures/"):
  553. filename = name.split("/")[-1]
  554. if filename:
  555. result["model_pictures"].append(
  556. {
  557. "name": filename,
  558. "path": name,
  559. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  560. }
  561. )
  562. elif name.startswith("Auxiliaries/Profile Pictures/"):
  563. filename = name.split("/")[-1]
  564. if filename:
  565. result["profile_pictures"].append(
  566. {
  567. "name": filename,
  568. "path": name,
  569. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  570. }
  571. )
  572. elif name.startswith("Auxiliaries/.thumbnails/"):
  573. filename = name.split("/")[-1]
  574. if filename:
  575. result["thumbnails"].append(
  576. {
  577. "name": filename,
  578. "path": name,
  579. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  580. }
  581. )
  582. except Exception as e:
  583. result["_error"] = str(e)
  584. return result
  585. def get_image(self, image_path: str) -> tuple[bytes, str] | None:
  586. """Extract an image from the 3MF file.
  587. Returns tuple of (image_data, content_type) or None if not found.
  588. """
  589. try:
  590. with zipfile.ZipFile(self.file_path, "r") as zf:
  591. if image_path in zf.namelist():
  592. data = zf.read(image_path)
  593. # Determine content type from extension
  594. ext = image_path.lower().split(".")[-1]
  595. content_types = {
  596. "png": "image/png",
  597. "jpg": "image/jpeg",
  598. "jpeg": "image/jpeg",
  599. "webp": "image/webp",
  600. "gif": "image/gif",
  601. }
  602. content_type = content_types.get(ext, "application/octet-stream")
  603. return (data, content_type)
  604. except Exception:
  605. pass # Return None if image cannot be extracted from 3MF
  606. return None
  607. def update_metadata(self, updates: dict) -> bool:
  608. """Update project page metadata in the 3MF file.
  609. Args:
  610. updates: Dict with fields to update (title, description, designer, etc.)
  611. Returns:
  612. True if successful, False otherwise.
  613. """
  614. import html
  615. import tempfile
  616. try:
  617. # Read the 3MF file
  618. with zipfile.ZipFile(self.file_path, "r") as zf_read:
  619. # Find and read the 3dmodel.model file
  620. model_path = "3D/3dmodel.model"
  621. if model_path not in zf_read.namelist():
  622. return False
  623. content = zf_read.read(model_path).decode("utf-8")
  624. # Update metadata fields
  625. field_mapping = {
  626. "title": "Title",
  627. "description": "Description",
  628. "designer": "Designer",
  629. "license": "License",
  630. "copyright": "Copyright",
  631. "profile_title": "ProfileTitle",
  632. "profile_description": "ProfileDescription",
  633. }
  634. for field, xml_name in field_mapping.items():
  635. if field in updates and updates[field] is not None:
  636. new_value = html.escape(updates[field])
  637. # Replace existing metadata or we'd need to add it
  638. pattern = rf'(<metadata\s+name="{xml_name}"[^>]*>)[^<]*(</metadata>)'
  639. replacement = rf"\g<1>{new_value}\g<2>"
  640. content = re.sub(pattern, replacement, content)
  641. # Write to a temporary file first
  642. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf") as tmp:
  643. tmp_path = Path(tmp.name)
  644. # Create new zip with updated content
  645. with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as zf_write:
  646. for item in zf_read.namelist():
  647. if item == model_path:
  648. zf_write.writestr(item, content.encode("utf-8"))
  649. else:
  650. zf_write.writestr(item, zf_read.read(item))
  651. # Replace original file with updated one
  652. shutil.move(tmp_path, self.file_path)
  653. return True
  654. except Exception:
  655. # Clean up temp file if it exists
  656. if "tmp_path" in locals() and tmp_path.exists():
  657. tmp_path.unlink()
  658. return False
  659. class ArchiveService:
  660. """Service for archiving print jobs."""
  661. def __init__(self, db: AsyncSession):
  662. self.db = db
  663. @staticmethod
  664. def compute_file_hash(file_path: Path) -> str:
  665. """Compute SHA256 hash of a file for duplicate detection."""
  666. sha256 = hashlib.sha256()
  667. with open(file_path, "rb") as f:
  668. # Read in chunks to handle large files
  669. for chunk in iter(lambda: f.read(8192), b""):
  670. sha256.update(chunk)
  671. return sha256.hexdigest()
  672. async def get_duplicate_hashes_and_names(self) -> tuple[set[str], set[tuple[str, str]]]:
  673. """Get all content hashes and (print name, hash) pairs that appear more than once.
  674. For hashes: returns all hashes with > 1 archive (true duplicates).
  675. For name/hash pairs: returns only pairs that have > 1 archive
  676. (i.e., same file archived multiple times, not different files with same name).
  677. Returns a tuple of (duplicate_hashes, duplicate_name_hash_pairs).
  678. """
  679. from sqlalchemy import func
  680. result = await self.db.execute(
  681. select(PrintArchive.content_hash)
  682. .where(PrintArchive.content_hash.isnot(None))
  683. .group_by(PrintArchive.content_hash)
  684. .having(func.count(PrintArchive.id) > 1)
  685. )
  686. duplicate_hashes = {row[0] for row in result.all()}
  687. # Find print names that have multiple archives with the SAME hash
  688. # This avoids marking different files with the same name as duplicates
  689. result = await self.db.execute(
  690. select(func.lower(PrintArchive.print_name), PrintArchive.content_hash)
  691. .where(PrintArchive.print_name.isnot(None), PrintArchive.content_hash.isnot(None))
  692. .group_by(func.lower(PrintArchive.print_name), PrintArchive.content_hash)
  693. .having(func.count(PrintArchive.id) > 1)
  694. )
  695. duplicate_name_hash_pairs = {(row[0], row[1]) for row in result.all()}
  696. return duplicate_hashes, duplicate_name_hash_pairs
  697. async def find_duplicates(
  698. self,
  699. archive_id: int,
  700. content_hash: str | None = None,
  701. print_name: str | None = None,
  702. makerworld_model_id: str | None = None,
  703. ) -> list[dict]:
  704. """Find duplicate archives based on hash or name matching.
  705. Returns list of dicts with id, print_name, created_at, match_type.
  706. """
  707. duplicates = []
  708. # First, find exact matches by content hash
  709. if content_hash:
  710. result = await self.db.execute(
  711. select(PrintArchive)
  712. .where(
  713. and_(
  714. PrintArchive.content_hash == content_hash,
  715. PrintArchive.id != archive_id,
  716. )
  717. )
  718. .order_by(PrintArchive.created_at.desc())
  719. .limit(10)
  720. )
  721. for archive in result.scalars().all():
  722. duplicates.append(
  723. {
  724. "id": archive.id,
  725. "print_name": archive.print_name,
  726. "created_at": archive.created_at,
  727. "match_type": "exact",
  728. }
  729. )
  730. # Then, find similar matches by print name or MakerWorld ID
  731. # Prefer strict name+hash matching when hash exists; fallback to name-only for legacy/manual
  732. # archives that may not have a content_hash.
  733. if print_name or makerworld_model_id:
  734. conditions = [PrintArchive.id != archive_id]
  735. name_conditions = []
  736. if print_name:
  737. if content_hash:
  738. # Match if print names are similar AND have the same hash (same file)
  739. name_conditions.append(
  740. and_(PrintArchive.print_name.ilike(print_name), PrintArchive.content_hash == content_hash)
  741. )
  742. else:
  743. # Fallback for archives without hash data: match by print name only.
  744. name_conditions.append(PrintArchive.print_name.ilike(print_name))
  745. if makerworld_model_id:
  746. # Match by MakerWorld model ID stored in extra_data
  747. from backend.app.core.db_dialect import is_sqlite
  748. if is_sqlite():
  749. from sqlalchemy import func
  750. name_conditions.append(
  751. func.json_extract(PrintArchive.extra_data, "$.makerworld_model_id") == str(makerworld_model_id)
  752. )
  753. else:
  754. name_conditions.append(
  755. text("(extra_data::jsonb->>'makerworld_model_id') = :mw_id").bindparams(
  756. mw_id=str(makerworld_model_id)
  757. )
  758. )
  759. if name_conditions:
  760. conditions.append(or_(*name_conditions))
  761. result = await self.db.execute(
  762. select(PrintArchive).where(and_(*conditions)).order_by(PrintArchive.created_at.desc()).limit(10)
  763. )
  764. for archive in result.scalars().all():
  765. # Don't add if already in duplicates (exact match)
  766. if not any(d["id"] == archive.id for d in duplicates):
  767. duplicates.append(
  768. {
  769. "id": archive.id,
  770. "print_name": archive.print_name,
  771. "created_at": archive.created_at,
  772. "match_type": "similar",
  773. }
  774. )
  775. return duplicates
  776. async def archive_print(
  777. self,
  778. printer_id: int | None,
  779. source_file: Path,
  780. print_data: dict | None = None,
  781. created_by_id: int | None = None,
  782. original_filename: str | None = None,
  783. project_id: int | None = None,
  784. subtask_id: str | None = None,
  785. prefer_filename_for_name: bool = False,
  786. ) -> PrintArchive | None:
  787. """Archive a 3MF file with metadata.
  788. Args:
  789. printer_id: ID of the printer (optional)
  790. source_file: Path to the 3MF file
  791. print_data: Print data from MQTT (optional)
  792. created_by_id: User ID who created this archive (optional, for user tracking)
  793. original_filename: Original human-readable filename (optional, for library files
  794. stored with UUID names)
  795. project_id: Project to associate this archive with (optional, set when triggered
  796. from the project view)
  797. subtask_id: MQTT-provided task identifier (optional). Used to match an
  798. existing archive across a backend restart mid-print so the
  799. original row can be resumed instead of cancelled (#972).
  800. prefer_filename_for_name: When True, use the uploaded filename stem as the
  801. archive's display name even if the 3MF embeds a `print_name` in its
  802. metadata. Used by virtual-printer flows so users who rename a job in
  803. BambuStudio's "send to printer" dialog see that name instead of the
  804. creator-baked title (#1152).
  805. """
  806. # Verify printer exists if specified
  807. if printer_id is not None:
  808. result = await self.db.execute(select(Printer).where(Printer.id == printer_id))
  809. printer = result.scalar_one_or_none()
  810. if not printer:
  811. return None
  812. # Create archive directory structure
  813. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  814. display_stem = resolve_display_stem(original_filename if original_filename else source_file.name)
  815. archive_name = f"{timestamp}_{display_stem}"
  816. # Use "unassigned" folder for archives without a printer
  817. printer_folder = str(printer_id) if printer_id is not None else "unassigned"
  818. archive_dir = settings.archive_dir / printer_folder / archive_name
  819. archive_dir.mkdir(parents=True, exist_ok=True)
  820. # Copy 3MF file with an explicit fsync'd loop (avoids a sendfile
  821. # short-read quirk that silently truncated 3MF archives on some
  822. # platforms — see _copy_and_fsync and #1032).
  823. dest_file = archive_dir / source_file.name
  824. _copy_and_fsync(source_file, dest_file)
  825. # If we just archived a 3MF, verify the dest is a valid ZIP before
  826. # going any further. Staying quiet here is how #1032 escaped review —
  827. # the archive row was written but every later zipfile.ZipFile() call
  828. # on the dest failed with "File is not a zip file".
  829. if (
  830. source_file.suffix.lower() == ".3mf"
  831. and zipfile.is_zipfile(source_file)
  832. and not zipfile.is_zipfile(dest_file)
  833. ):
  834. try:
  835. src_size = source_file.stat().st_size
  836. dst_size = dest_file.stat().st_size
  837. except OSError:
  838. src_size = dst_size = -1
  839. logger.error(
  840. "Archive copy corrupted 3MF: src=%s (%s bytes, valid ZIP) -> dst=%s (%s bytes, NOT a ZIP). Refusing to create archive row.",
  841. source_file,
  842. src_size,
  843. dest_file,
  844. dst_size,
  845. )
  846. # Narrow cleanup: remove only the truncated file and the archive
  847. # directory if it's now empty. archive_dir was created with
  848. # exist_ok=True so it could in theory pre-date this call (e.g.
  849. # same-second same-filename collision); rmtree would be too broad.
  850. try:
  851. dest_file.unlink()
  852. except OSError:
  853. pass
  854. try:
  855. archive_dir.rmdir()
  856. except OSError:
  857. pass # directory not empty — leave untouched
  858. return None
  859. # Compute content hash for duplicate detection
  860. content_hash = self.compute_file_hash(dest_file)
  861. # Extract plate number from filename (e.g., "plate_5" from "/data/Metadata/plate_5.gcode")
  862. plate_number = None
  863. if print_data:
  864. filename = print_data.get("filename", "")
  865. match = re.search(r"plate_(\d+)", filename)
  866. if match:
  867. plate_number = int(match.group(1))
  868. # Parse 3MF metadata
  869. parser = ThreeMFParser(dest_file, plate_number=plate_number)
  870. metadata = parser.parse()
  871. # Save thumbnail if present
  872. thumbnail_path = None
  873. if "_thumbnail_data" in metadata:
  874. thumb_file = archive_dir / f"thumbnail{metadata['_thumbnail_ext']}"
  875. thumb_file.write_bytes(metadata["_thumbnail_data"])
  876. thumbnail_path = str(thumb_file.relative_to(settings.base_dir))
  877. del metadata["_thumbnail_data"]
  878. del metadata["_thumbnail_ext"]
  879. # Merge with print data from MQTT
  880. if print_data:
  881. metadata["_print_data"] = print_data
  882. # Determine status and timestamps
  883. status = print_data.get("status", "completed") if print_data else "archived"
  884. started_at = datetime.now(timezone.utc) if status == "printing" else None
  885. completed_at = datetime.now(timezone.utc) if status in ("completed", "failed", "archived") else None
  886. # Calculate cost based on filament usage and type
  887. cost = None
  888. filament_grams = metadata.get("filament_used_grams")
  889. filament_type = metadata.get("filament_type")
  890. if filament_grams and filament_type:
  891. # For multi-material prints, use the first filament type for cost calculation
  892. primary_type = filament_type.split(",")[0].strip()
  893. # Look up filament cost_per_kg from database
  894. filament_result = await self.db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  895. filament = filament_result.scalar_one_or_none()
  896. if filament:
  897. cost = round((filament_grams / 1000) * filament.cost_per_kg, 2)
  898. else:
  899. # Use default filament cost from settings
  900. from backend.app.api.routes.settings import get_setting
  901. default_cost_setting = await get_setting(self.db, "default_filament_cost")
  902. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  903. cost = round((filament_grams / 1000) * default_cost_per_kg, 2)
  904. # Calculate quantity from printable objects count
  905. # printable_objects is a dict of {identify_id: name} for non-skipped objects
  906. quantity = 1 # Default to 1
  907. printable_objects = metadata.get("printable_objects")
  908. if printable_objects and isinstance(printable_objects, dict):
  909. quantity = len(printable_objects)
  910. logger.debug("Auto-detected %s parts from 3MF printable objects", quantity)
  911. # Create archive record
  912. archive = PrintArchive(
  913. printer_id=printer_id,
  914. filename=original_filename or source_file.name,
  915. file_path=str(dest_file.relative_to(settings.base_dir)),
  916. file_size=dest_file.stat().st_size,
  917. content_hash=content_hash,
  918. thumbnail_path=thumbnail_path,
  919. print_name=display_stem if prefer_filename_for_name else (metadata.get("print_name") or display_stem),
  920. print_time_seconds=metadata.get("print_time_seconds"),
  921. filament_used_grams=metadata.get("filament_used_grams"),
  922. filament_type=metadata.get("filament_type"),
  923. filament_color=metadata.get("filament_color"),
  924. layer_height=metadata.get("layer_height"),
  925. total_layers=metadata.get("total_layers"),
  926. nozzle_diameter=metadata.get("nozzle_diameter"),
  927. bed_temperature=metadata.get("bed_temperature"),
  928. nozzle_temperature=metadata.get("nozzle_temperature"),
  929. sliced_for_model=metadata.get("sliced_for_model"),
  930. makerworld_url=metadata.get("makerworld_url"),
  931. designer=metadata.get("designer"),
  932. status=status,
  933. started_at=started_at,
  934. completed_at=completed_at,
  935. cost=cost,
  936. quantity=quantity,
  937. extra_data=metadata,
  938. created_by_id=created_by_id,
  939. project_id=project_id,
  940. subtask_id=subtask_id,
  941. )
  942. self.db.add(archive)
  943. await self.db.commit()
  944. await self.db.refresh(archive)
  945. return archive
  946. async def get_archive(self, archive_id: int) -> PrintArchive | None:
  947. """Get an archive by ID with relationships loaded."""
  948. from sqlalchemy.orm import selectinload
  949. result = await self.db.execute(
  950. select(PrintArchive)
  951. .options(selectinload(PrintArchive.created_by), selectinload(PrintArchive.project))
  952. .where(PrintArchive.id == archive_id)
  953. )
  954. return result.scalar_one_or_none()
  955. async def update_archive_status(
  956. self,
  957. archive_id: int,
  958. status: str,
  959. completed_at: datetime | None = None,
  960. failure_reason: str | None = None,
  961. ) -> bool:
  962. """Update the status of an archive."""
  963. archive = await self.get_archive(archive_id)
  964. if not archive:
  965. return False
  966. archive.status = status
  967. if completed_at:
  968. archive.completed_at = completed_at
  969. if failure_reason:
  970. archive.failure_reason = failure_reason
  971. await self.db.commit()
  972. return True
  973. async def list_archives(
  974. self,
  975. printer_id: int | None = None,
  976. project_id: int | None = None,
  977. date_from: date | None = None,
  978. date_to: date | None = None,
  979. limit: int = 50,
  980. offset: int = 0,
  981. ) -> list[PrintArchive]:
  982. """List archives with optional filtering."""
  983. from sqlalchemy.orm import selectinload
  984. query = (
  985. select(PrintArchive)
  986. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  987. .order_by(PrintArchive.created_at.desc())
  988. )
  989. if printer_id:
  990. query = query.where(PrintArchive.printer_id == printer_id)
  991. if project_id:
  992. query = query.where(PrintArchive.project_id == project_id)
  993. if date_from:
  994. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  995. query = query.where(PrintArchive.created_at >= dt_from)
  996. if date_to:
  997. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  998. query = query.where(PrintArchive.created_at <= dt_to)
  999. query = query.limit(limit).offset(offset)
  1000. result = await self.db.execute(query)
  1001. return list(result.scalars().all())
  1002. async def delete_archive(self, archive_id: int) -> bool:
  1003. """Delete an archive and its files."""
  1004. archive = await self.get_archive(archive_id)
  1005. if not archive:
  1006. return False
  1007. # Resolve the directory to delete BEFORE committing the DB change
  1008. dir_to_delete: Path | None = None
  1009. if archive.file_path and archive.file_path.strip():
  1010. file_path = settings.base_dir / archive.file_path
  1011. if file_path.exists():
  1012. archive_dir = file_path.parent
  1013. # Safety check 1: archive_dir must be inside archive_dir
  1014. try:
  1015. archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1016. except ValueError:
  1017. logger.error(
  1018. f"SECURITY: Refusing to delete archive {archive_id} - "
  1019. f"path {archive_dir} is outside archive directory {settings.archive_dir}"
  1020. )
  1021. await self.db.delete(archive)
  1022. await self.db.commit()
  1023. return True
  1024. # Safety check 2: archive_dir must be at least 1 level deep inside archive_dir
  1025. try:
  1026. relative_path = archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1027. if len(relative_path.parts) < 1:
  1028. logger.error(
  1029. f"SECURITY: Refusing to delete archive {archive_id} - "
  1030. f"path {archive_dir} is not deep enough inside archive directory"
  1031. )
  1032. await self.db.delete(archive)
  1033. await self.db.commit()
  1034. return True
  1035. except ValueError:
  1036. pass # Already handled above
  1037. dir_to_delete = archive_dir
  1038. else:
  1039. logger.error(
  1040. f"SECURITY: Refusing to delete files for archive {archive_id} - "
  1041. f"file_path is empty or invalid: '{archive.file_path}'"
  1042. )
  1043. # Delete database record FIRST — if the commit fails (e.g. database locked
  1044. # during concurrent bulk deletes), the files stay on disk and nothing is lost.
  1045. await self.db.delete(archive)
  1046. await self.db.commit()
  1047. # Only delete files AFTER the DB commit succeeds to avoid orphaned records
  1048. if dir_to_delete:
  1049. shutil.rmtree(dir_to_delete, ignore_errors=True)
  1050. return True
  1051. async def attach_timelapse(
  1052. self,
  1053. archive_id: int,
  1054. timelapse_data: bytes,
  1055. filename: str = "timelapse.mp4",
  1056. ) -> bool:
  1057. """Attach a timelapse video to an archive.
  1058. Non-MP4 videos (e.g. AVI from P1S) are saved as-is and a background
  1059. task converts them to MP4 for browser compatibility.
  1060. """
  1061. import asyncio
  1062. archive = await self.get_archive(archive_id)
  1063. if not archive:
  1064. return False
  1065. # Get archive directory
  1066. file_path = settings.base_dir / archive.file_path
  1067. archive_dir = file_path.parent
  1068. # Save timelapse - use thread pool to avoid blocking event loop
  1069. # (timelapse files can be 100MB+, sync write blocks for seconds)
  1070. timelapse_file = archive_dir / filename
  1071. await asyncio.to_thread(timelapse_file.write_bytes, timelapse_data)
  1072. # Update archive record
  1073. archive.timelapse_path = str(timelapse_file.relative_to(settings.base_dir))
  1074. await self.db.commit()
  1075. # For non-MP4 videos (e.g. AVI from P1S), kick off background conversion
  1076. if not filename.lower().endswith(".mp4"):
  1077. asyncio.create_task(
  1078. _convert_timelapse_to_mp4(archive_id, timelapse_file),
  1079. name=f"timelapse-convert-{archive_id}",
  1080. )
  1081. return True
  1082. async def _convert_timelapse_to_mp4(archive_id: int, source_path: Path) -> None:
  1083. """Background task: convert non-MP4 timelapse (e.g. AVI from P1S) to MP4.
  1084. Runs with low CPU priority (-threads 1, nice) so it doesn't starve
  1085. other processes on resource-constrained devices like Raspberry Pi.
  1086. """
  1087. import asyncio
  1088. from backend.app.core.database import async_session
  1089. from backend.app.services.camera import get_ffmpeg_path
  1090. logger = logging.getLogger(__name__)
  1091. ffmpeg = get_ffmpeg_path()
  1092. if not ffmpeg:
  1093. logger.info(
  1094. "FFmpeg not available, skipping timelapse conversion for archive %s (file saved as %s)",
  1095. archive_id,
  1096. source_path.suffix,
  1097. )
  1098. return
  1099. mp4_path = source_path.with_suffix(".mp4")
  1100. try:
  1101. cmd = [
  1102. ffmpeg,
  1103. "-y",
  1104. "-i",
  1105. str(source_path),
  1106. "-c:v",
  1107. "libx264",
  1108. "-preset",
  1109. "fast",
  1110. "-crf",
  1111. "23",
  1112. "-threads",
  1113. "1",
  1114. "-movflags",
  1115. "+faststart",
  1116. str(mp4_path),
  1117. ]
  1118. # Try with nice for lower CPU priority (standard on Linux/macOS)
  1119. try:
  1120. process = await asyncio.create_subprocess_exec(
  1121. "nice",
  1122. "-n",
  1123. "19",
  1124. *cmd,
  1125. stdout=asyncio.subprocess.PIPE,
  1126. stderr=asyncio.subprocess.PIPE,
  1127. )
  1128. except FileNotFoundError:
  1129. # nice not available (e.g. Windows), run without
  1130. process = await asyncio.create_subprocess_exec(
  1131. *cmd,
  1132. stdout=asyncio.subprocess.PIPE,
  1133. stderr=asyncio.subprocess.PIPE,
  1134. )
  1135. _, stderr = await process.communicate()
  1136. if process.returncode != 0:
  1137. logger.warning(
  1138. "Timelapse conversion failed for archive %s: %s",
  1139. archive_id,
  1140. stderr.decode()[-500:],
  1141. )
  1142. if mp4_path.exists():
  1143. mp4_path.unlink()
  1144. return
  1145. # Update DB path to the new MP4 file
  1146. async with async_session() as db:
  1147. from backend.app.models.archive import PrintArchive
  1148. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1149. archive = result.scalar_one_or_none()
  1150. if archive:
  1151. archive.timelapse_path = str(mp4_path.relative_to(settings.base_dir))
  1152. await db.commit()
  1153. # Remove original non-MP4 file
  1154. if source_path.exists():
  1155. source_path.unlink()
  1156. logger.info(
  1157. "Converted timelapse to MP4 for archive %s (%s → %s)",
  1158. archive_id,
  1159. source_path.name,
  1160. mp4_path.name,
  1161. )
  1162. except Exception as e:
  1163. logger.warning("Timelapse conversion error for archive %s: %s", archive_id, e)
  1164. if mp4_path.exists():
  1165. mp4_path.unlink()