archive.py 59 KB

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