archive.py 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  1. import hashlib
  2. import html
  3. import json
  4. import logging
  5. import os
  6. import re
  7. import shutil
  8. import zipfile
  9. from datetime import date, datetime, time, timezone
  10. from pathlib import Path
  11. from defusedxml import ElementTree as ET
  12. from sqlalchemy import and_, or_, select, text
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from backend.app.core.config import settings
  15. from backend.app.core.tasks import spawn_background_task
  16. from backend.app.models.archive import PrintArchive
  17. from backend.app.models.filament import Filament
  18. from backend.app.models.printer import Printer
  19. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  20. from backend.app.utils.filename import clean_display_name
  21. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  22. logger = logging.getLogger(__name__)
  23. def _copy_and_fsync(src: Path, dst: Path, chunk_size: int = 1024 * 1024) -> None:
  24. """Copy src to dst with an explicit chunked read/write and fsync the dst.
  25. Replacement for shutil.copy2 in the archive pipeline. shutil.copy2 uses
  26. Linux sendfile(), which on some kernels/filesystems has returned a short
  27. count on the first call and truncated the destination for larger 3MF
  28. uploads (#1032, observed on Raspberry Pi OS bookworm / armv7l). An
  29. explicit loop with fsync avoids that path and guarantees the dest bytes
  30. are on disk before the caller inspects them as a ZIP.
  31. """
  32. with src.open("rb") as rf, dst.open("wb") as wf:
  33. while True:
  34. buf = rf.read(chunk_size)
  35. if not buf:
  36. break
  37. wf.write(buf)
  38. wf.flush()
  39. os.fsync(wf.fileno())
  40. shutil.copystat(src, dst)
  41. def resolve_display_stem(filename: str) -> str:
  42. """Return a clean human-readable stem from a 3MF/gcode filename.
  43. Bambu Studio's "Send to printer" dialog typically writes files like
  44. ``Plate_1.gcode.3mf`` (a sliced gcode payload wrapped in a 3MF container).
  45. The naive ``Path(filename).stem`` only drops the last suffix, leaving
  46. ``Plate_1.gcode`` — which then surfaces in the archive UI as a confusing
  47. ``Plate_1.gcode`` rather than ``Plate_1`` (#1152 follow-up).
  48. Strip the recognised print-format suffixes in order:
  49. - ``.gcode.3mf`` → bare stem (Bambu Studio FTP send)
  50. - ``.3mf`` → bare stem
  51. - ``.gcode`` → bare stem (rare standalone gcode upload)
  52. Anything else passes through unchanged.
  53. """
  54. name = Path(filename).name # drop any path components
  55. lower = name.lower()
  56. for suffix in (".gcode.3mf", ".3mf", ".gcode"):
  57. if lower.endswith(suffix):
  58. return name[: -len(suffix)]
  59. return Path(name).stem
  60. def _read_plate_index(plate) -> int | None:
  61. """Return the 1-based index of a ``slice_info.config`` ``<plate>`` element, or None.
  62. Bambu Studio and OrcaSlicer record it as a ``<metadata key="index"
  63. value="N"/>`` child — there is no ``plate_idx`` attribute on ``<plate>``
  64. itself, so an XPath predicate on one never matches (#2522).
  65. """
  66. for meta in plate.findall("metadata"):
  67. if meta.get("key") == "index":
  68. value = meta.get("value")
  69. if not value:
  70. return None
  71. try:
  72. return int(value)
  73. except ValueError:
  74. return None
  75. return None
  76. def peek_plate_index_in_3mf(file_path: Path) -> int | None:
  77. """Return the plate index a single-plate Bambu 3MF represents, or None.
  78. Reads only ``Metadata/slice_info.config`` to keep this cheap — used by
  79. the print-start callback to verify that the 3MF we just downloaded over
  80. FTP actually matches the plate the printer is running (#1204). The full
  81. ThreeMFParser does much more work and runs later inside ArchiveService.
  82. An all-plates export carries every plate, so "which plate is this file"
  83. has no answer; returning None there keeps the #1204 guard from reading
  84. plate 1 out of such a file, declaring a mismatch against the plate that
  85. is really running, and discarding a perfectly good 3MF (#2522).
  86. """
  87. try:
  88. with zipfile.ZipFile(file_path, "r") as zf:
  89. if "Metadata/slice_info.config" not in zf.namelist():
  90. return None
  91. content = zf.read("Metadata/slice_info.config").decode()
  92. root = ET.fromstring(content)
  93. plates = root.findall(".//plate")
  94. if len(plates) != 1:
  95. return None
  96. return _read_plate_index(plates[0])
  97. except Exception:
  98. return None
  99. _PLATE_SUFFIX_RE = re.compile(r"^(.*?)(\s*-\s*Plate\s+|_plate_)(\d+)$", re.IGNORECASE)
  100. def swap_plate_suffix(name: str | None, target_plate: int) -> str | None:
  101. """Return ``name`` with its trailing plate number replaced, or None.
  102. Bambu Studio names multi-plate uploads ``"<Project> - Plate <N>"`` (and
  103. a lowercase ``"_plate_<N>"`` variant exists too — see
  104. test_print_start_expected_promotion). When MQTT subtask_name lags
  105. across consecutive plates of the same model (#1204) the suffix points
  106. at the previous plate; swapping it gives us the correct upload to
  107. re-fetch from FTP. Returns None if no recognised suffix is present.
  108. """
  109. if not name:
  110. return None
  111. m = _PLATE_SUFFIX_RE.match(name)
  112. if not m:
  113. return None
  114. base, separator, _ = m.groups()
  115. return f"{base}{separator}{target_plate}"
  116. class ThreeMFParser:
  117. """Parser for Bambu Lab 3MF files."""
  118. def __init__(self, file_path: Path, plate_number: int | None = None):
  119. self.file_path = file_path
  120. self.plate_number = plate_number # Which plate was printed (1, 2, 3, etc.)
  121. self.metadata: dict = {}
  122. def parse(self) -> dict:
  123. """Extract metadata from 3MF file."""
  124. try:
  125. with zipfile.ZipFile(self.file_path, "r") as zf:
  126. self._parse_slice_info(zf) # Now sets self.plate_number from slice_info
  127. self._parse_project_settings(zf)
  128. self._parse_gcode_header(zf)
  129. self._parse_3dmodel(zf)
  130. self._extract_thumbnail(zf) # Uses correct plate_number for thumbnail
  131. # Enhance print_name with plate info if this is a multi-plate export
  132. plate_index = self.metadata.get("_plate_index")
  133. if plate_index and plate_index > 1:
  134. # Append plate number to distinguish from other plates
  135. existing_name = self.metadata.get("print_name", "")
  136. if existing_name and f"Plate {plate_index}" not in existing_name:
  137. self.metadata["print_name"] = f"{existing_name} - Plate {plate_index}"
  138. # ALWAYS prefer slice_info values - they contain ONLY filaments actually used in print
  139. # project_settings contains ALL configured filaments (AMS slots), not just used ones
  140. if self.metadata.get("_slice_filament_type"):
  141. self.metadata["filament_type"] = self.metadata["_slice_filament_type"]
  142. if self.metadata.get("_slice_filament_color"):
  143. self.metadata["filament_color"] = self.metadata["_slice_filament_color"]
  144. # Clean up internal keys
  145. self.metadata.pop("_slice_filament_type", None)
  146. self.metadata.pop("_slice_filament_color", None)
  147. self.metadata.pop("_plate_index", None)
  148. except Exception as e:
  149. # Return whatever metadata was extracted before the error, but
  150. # surface the failure so corrupted / truncated 3MF archives are
  151. # visible in support bundles (#1032).
  152. logger.warning(
  153. "ThreeMFParser: failed to parse %s: %s(%s) — returning partial metadata",
  154. self.file_path,
  155. type(e).__name__,
  156. e,
  157. )
  158. return self.metadata
  159. def _parse_slice_info(self, zf: zipfile.ZipFile):
  160. """Parse slice_info.config for print settings and printable objects."""
  161. try:
  162. if "Metadata/slice_info.config" in zf.namelist():
  163. content = zf.read("Metadata/slice_info.config").decode()
  164. root = ET.fromstring(content)
  165. # Extract printer_model_id from plate metadata
  166. # Format: <plate><metadata key="printer_model_id" value="C11" /></plate>
  167. for meta in root.findall(".//metadata"):
  168. key = meta.get("key")
  169. value = meta.get("value")
  170. if key == "printer_model_id" and value:
  171. from backend.app.utils.printer_models import normalize_printer_model_id
  172. normalized = normalize_printer_model_id(value)
  173. if normalized:
  174. self.metadata["sliced_for_model"] = normalized
  175. break
  176. # Loop every <plate> so multi-plate exports get summed file-level
  177. # totals. Pre-fix, this used `root.find(".//plate")` which
  178. # returned only the first plate — file-level `print_time_seconds`
  179. # / `filament_used_grams` reflected plate 1 alone, and the
  180. # archive card / project rollup under-reported by the number
  181. # of plates (#1593). Per-plate breakdown is still served by
  182. # the dedicated `/plates` endpoint.
  183. plates = root.findall(".//plate")
  184. summed_time = 0
  185. summed_grams = 0.0
  186. any_time_seen = False
  187. any_grams_seen = False
  188. for plate in plates:
  189. # Plate-level fields that only make sense at the file
  190. # level when there's exactly one plate. ``plate_number``
  191. # / ``_plate_index`` describe which plate the export
  192. # represents — meaningless for an all-plates 3MF, so we
  193. # only record them in the single-plate case. ``bed_type``
  194. # is also single-valued; we take the first plate's value
  195. # as a best-effort default for the archive metadata.
  196. plate_index_value: int | None = None
  197. for meta in plate.findall("metadata"):
  198. key = meta.get("key")
  199. value = meta.get("value")
  200. if key == "index" and value:
  201. try:
  202. plate_index_value = int(value)
  203. except ValueError:
  204. pass # Skip non-numeric plate index
  205. elif key == "prediction" and value:
  206. try:
  207. summed_time += int(value)
  208. any_time_seen = True
  209. except ValueError:
  210. pass
  211. elif key == "weight" and value:
  212. try:
  213. summed_grams += float(value)
  214. any_grams_seen = True
  215. except ValueError:
  216. pass
  217. elif key == "curr_bed_type" and value and "bed_type" not in self.metadata:
  218. self.metadata["bed_type"] = value
  219. # Per-plate object lists are only kept at the file level
  220. # when there's one plate — the skip-object affordance
  221. # operates on the plate being printed, which is the
  222. # `/plates` endpoint's job for multi-plate exports.
  223. if len(plates) == 1:
  224. if plate_index_value is not None:
  225. if not self.plate_number:
  226. self.plate_number = plate_index_value
  227. self.metadata["_plate_index"] = plate_index_value
  228. printable_objects: dict[int, str] = {}
  229. for obj in plate.findall("object"):
  230. identify_id = obj.get("identify_id")
  231. name = obj.get("name")
  232. skipped = obj.get("skipped", "false")
  233. if identify_id and name and skipped.lower() != "true":
  234. try:
  235. printable_objects[int(identify_id)] = name
  236. except ValueError:
  237. pass # Skip objects with non-numeric identify_id
  238. if printable_objects:
  239. self.metadata["printable_objects"] = printable_objects
  240. if any_time_seen:
  241. self.metadata["print_time_seconds"] = summed_time
  242. if any_grams_seen:
  243. self.metadata["filament_used_grams"] = round(summed_grams, 2)
  244. # Get filament info from filaments ACTUALLY USED in the print
  245. # slice_info has <filament id="1" type="PLA" color="#FFFFFF" used_g="100" />
  246. # Only include filaments where used_g > 0
  247. filaments = root.findall(".//filament")
  248. if filaments:
  249. # Collect unique filament types and colors for filaments that are actually used
  250. types = []
  251. colors = []
  252. for f in filaments:
  253. # Check if this filament is actually used in the print
  254. used_g = f.get("used_g", "0")
  255. try:
  256. used_amount = float(used_g)
  257. except (ValueError, TypeError):
  258. used_amount = 0
  259. # Only include if used_g > 0 (filament is actually consumed)
  260. if used_amount > 0:
  261. ftype = f.get("type")
  262. fcolor = f.get("color")
  263. if ftype and ftype not in types:
  264. types.append(ftype)
  265. if fcolor and fcolor not in colors:
  266. colors.append(fcolor)
  267. if types:
  268. self.metadata["_slice_filament_type"] = ", ".join(types)
  269. if colors:
  270. self.metadata["_slice_filament_color"] = ",".join(colors)
  271. # Collect per-slot filament usage for tracking & notifications
  272. filament_slots = []
  273. for f in filaments:
  274. slot_id = f.get("id")
  275. used_g_str = f.get("used_g", "0")
  276. try:
  277. used_g = float(used_g_str)
  278. except (ValueError, TypeError):
  279. used_g = 0
  280. if used_g > 0 and slot_id:
  281. filament_slots.append(
  282. {
  283. "slot_id": int(slot_id),
  284. "used_g": round(used_g, 2),
  285. "type": f.get("type", ""),
  286. "color": f.get("color", ""),
  287. }
  288. )
  289. if filament_slots:
  290. self.metadata["filament_slots"] = filament_slots
  291. except Exception:
  292. pass # Skip unparseable slice_info metadata
  293. def _parse_project_settings(self, zf: zipfile.ZipFile):
  294. """Parse project settings for print configuration."""
  295. try:
  296. if "Metadata/project_settings.config" in zf.namelist():
  297. content = zf.read("Metadata/project_settings.config").decode()
  298. try:
  299. data = json.loads(content)
  300. self._extract_filament_info(data)
  301. self._extract_print_settings(data)
  302. except json.JSONDecodeError:
  303. pass # Skip malformed project_settings JSON
  304. except Exception:
  305. pass # Skip unreadable project settings file
  306. def _parse_gcode_header(self, zf: zipfile.ZipFile):
  307. """Parse G-code file header for total layer count and printer model."""
  308. try:
  309. # Look for plate_1.gcode or similar
  310. gcode_files = [f for f in zf.namelist() if f.endswith(".gcode")]
  311. if not gcode_files:
  312. return
  313. # Read first 4KB of G-code (header contains metadata)
  314. gcode_path = gcode_files[0]
  315. with zf.open(gcode_path) as f:
  316. header = f.read(4096).decode("utf-8", errors="ignore")
  317. # Look for "; total layer number: XX" pattern
  318. match = re.search(r";\s*total\s+layer\s+number[:\s]+(\d+)", header, re.IGNORECASE)
  319. if match:
  320. self.metadata["total_layers"] = int(match.group(1))
  321. # Total filament usage. The slicer writes the print's totals into
  322. # the G-code header ("; total filament weight [g] : 126.26"). Only
  323. # a fallback — slice_info.config is more authoritative when present
  324. # — but it covers sliced outputs whose slice_info lacks per-filament
  325. # used_g, and it's the slicer's own figure regardless.
  326. if "filament_used_grams" not in self.metadata:
  327. match = re.search(r";\s*total\s+filament\s+weight\s*\[g\]\s*:\s*([\d.]+)", header, re.IGNORECASE)
  328. if match:
  329. self.metadata["filament_used_grams"] = float(match.group(1))
  330. if "filament_used_mm" not in self.metadata:
  331. match = re.search(r";\s*total\s+filament\s+length\s*\[mm\]\s*:\s*([\d.]+)", header, re.IGNORECASE)
  332. if match:
  333. self.metadata["filament_used_mm"] = float(match.group(1))
  334. # Look for printer_model in gcode header (fallback if not found in slice_info)
  335. # Format: "; printer_model = Bambu Lab X1 Carbon" or "; printer_model = X1C"
  336. if "sliced_for_model" not in self.metadata:
  337. match = re.search(r";\s*printer_model\s*=\s*(.+)", header, re.IGNORECASE)
  338. if match:
  339. from backend.app.utils.printer_models import normalize_printer_model
  340. raw_model = match.group(1).strip()
  341. self.metadata["sliced_for_model"] = normalize_printer_model(raw_model)
  342. except Exception:
  343. pass # G-code header parsing is best-effort; metadata may come from other sources
  344. def _extract_filament_info(self, data: dict):
  345. """Extract filament info from project settings — includes support
  346. materials so a PLA-model / PVA-support project shows both on the
  347. archive card badge (#1881).
  348. Earlier code filtered by ``filament_is_support``; that hid PVA
  349. (and any other soluble/breakaway support material) from the card
  350. even when the user had explicitly configured it, and made source
  351. 3MFs look single-material until the print completed. slice_info
  352. (parsed separately) is still preferred when present — it lists
  353. only filaments the print actually consumes, this fallback only
  354. runs on unsliced source 3MFs.
  355. """
  356. try:
  357. filament_types = data.get("filament_type", [])
  358. filament_colors = data.get("filament_colour", [])
  359. if not filament_types:
  360. return
  361. unique_types: list[str] = []
  362. for ftype in filament_types:
  363. if ftype and ftype not in unique_types:
  364. unique_types.append(ftype)
  365. unique_colors: list[str] = []
  366. for color in filament_colors:
  367. if color and color not in unique_colors:
  368. unique_colors.append(color)
  369. if unique_types:
  370. self.metadata["filament_type"] = ", ".join(unique_types)
  371. if unique_colors:
  372. self.metadata["filament_color"] = ",".join(unique_colors)
  373. except Exception:
  374. pass # Filament info is optional; fall back to slice_info values
  375. def _extract_print_settings(self, data: dict):
  376. """Extract print settings from JSON config."""
  377. try:
  378. # Layer height - usually an array, get first value
  379. if "layer_height" in data:
  380. val = data["layer_height"]
  381. if isinstance(val, list) and val:
  382. self.metadata["layer_height"] = float(val[0])
  383. elif isinstance(val, (int, float, str)):
  384. self.metadata["layer_height"] = float(val)
  385. # Nozzle diameter
  386. if "nozzle_diameter" in data:
  387. val = data["nozzle_diameter"]
  388. if isinstance(val, list) and val:
  389. self.metadata["nozzle_diameter"] = float(val[0])
  390. elif isinstance(val, (int, float, str)):
  391. self.metadata["nozzle_diameter"] = float(val)
  392. # Bed temperature - first layer or regular
  393. for key in ["bed_temperature_initial_layer", "bed_temperature"]:
  394. if key in data:
  395. val = data[key]
  396. if isinstance(val, list) and val:
  397. self.metadata["bed_temperature"] = int(float(val[0]))
  398. elif isinstance(val, (int, float, str)):
  399. self.metadata["bed_temperature"] = int(float(val))
  400. break
  401. # Nozzle temperature
  402. for key in ["nozzle_temperature_initial_layer", "nozzle_temperature"]:
  403. if key in data:
  404. val = data[key]
  405. if isinstance(val, list) and val:
  406. self.metadata["nozzle_temperature"] = int(float(val[0]))
  407. elif isinstance(val, (int, float, str)):
  408. self.metadata["nozzle_temperature"] = int(float(val))
  409. break
  410. # Printer model (extract and normalize)
  411. if "printer_model" in data:
  412. from backend.app.utils.printer_models import normalize_printer_model
  413. self.metadata["sliced_for_model"] = normalize_printer_model(data["printer_model"])
  414. # Build plate type — only set from project_settings if slice_info didn't already
  415. # provide it (slice_info is more authoritative as it reflects the exported plate).
  416. if "bed_type" not in self.metadata and "curr_bed_type" in data:
  417. val = data["curr_bed_type"]
  418. if isinstance(val, str) and val.strip():
  419. self.metadata["bed_type"] = val.strip()
  420. except Exception:
  421. pass # Print settings are optional; missing values are left unset
  422. def _extract_settings_from_content(self, content: str):
  423. """Extract print settings from config content."""
  424. settings_map = {
  425. "layer_height": ("layer_height", float),
  426. "nozzle_diameter": ("nozzle_diameter", float),
  427. "bed_temperature": ("bed_temperature", int),
  428. "nozzle_temperature": ("nozzle_temperature", int),
  429. }
  430. for key, (search_key, converter) in settings_map.items():
  431. if key not in self.metadata:
  432. try:
  433. # Try JSON format
  434. if f'"{search_key}"' in content:
  435. start = content.find(f'"{search_key}"')
  436. value_start = content.find(":", start) + 1
  437. value_end = content.find(",", value_start)
  438. if value_end == -1:
  439. value_end = content.find("}", value_start)
  440. value = content[value_start:value_end].strip().strip('"')
  441. self.metadata[key] = converter(value)
  442. except (ValueError, TypeError):
  443. pass # Skip settings with unconvertible values
  444. def _parse_3dmodel(self, zf: zipfile.ZipFile):
  445. """Parse 3D/3dmodel.model for MakerWorld metadata."""
  446. try:
  447. model_path = "3D/3dmodel.model"
  448. if model_path not in zf.namelist():
  449. return
  450. content = zf.read(model_path).decode("utf-8", errors="ignore")
  451. # Parse XML metadata elements
  452. # MakerWorld adds metadata like: <metadata name="Designer">username</metadata>
  453. metadata_pattern = r'<metadata\s+name="([^"]+)"[^>]*>([^<]*)</metadata>'
  454. matches = re.findall(metadata_pattern, content)
  455. # 3MF metadata values are XML-encoded — `&` becomes `&amp;`, etc.
  456. # ProjectPageParser learned this the hard way: BambuStudio sometimes
  457. # writes triple-encoded payloads (`&amp;amp;amp;`), so we unescape
  458. # in a loop until the string stabilises. Without this, a Title like
  459. # "Foo & Bar" lands in the DB as raw "Foo &amp; Bar" and React then
  460. # double-escapes it on render to "Foo &amp;amp; Bar" (#1658).
  461. makerworld_fields = {}
  462. for name, value in matches:
  463. decoded = value.strip()
  464. prev = None
  465. while prev != decoded:
  466. prev = decoded
  467. decoded = html.unescape(decoded)
  468. makerworld_fields[name] = decoded
  469. # Check for direct MakerWorld URL in content
  470. url_pattern = r'https?://makerworld\.com/[^\s<>"\']+/models/(\d+)'
  471. url_match = re.search(url_pattern, content)
  472. if url_match:
  473. self.metadata["makerworld_url"] = url_match.group(0)
  474. self.metadata["makerworld_model_id"] = url_match.group(1)
  475. # Extract model ID from DSM reference in image URLs
  476. # Format: https://makerworld.bblmw.com/makerworld/model/DSM00000001275614/...
  477. # The numeric part (1275614) is the MakerWorld model ID
  478. if "makerworld_url" not in self.metadata:
  479. dsm_pattern = r"DSM0+(\d+)"
  480. dsm_match = re.search(dsm_pattern, content)
  481. if dsm_match:
  482. model_id = dsm_match.group(1)
  483. self.metadata["makerworld_url"] = f"https://makerworld.com/en/models/{model_id}"
  484. self.metadata["makerworld_model_id"] = model_id
  485. # Store designer info
  486. if "Designer" in makerworld_fields:
  487. self.metadata["designer"] = makerworld_fields["Designer"]
  488. if "Title" in makerworld_fields:
  489. self.metadata["print_name"] = makerworld_fields["Title"]
  490. except Exception:
  491. pass # MakerWorld/3dmodel metadata is optional
  492. def _extract_thumbnail(self, zf: zipfile.ZipFile):
  493. """Extract thumbnail image from 3MF.
  494. If a plate_number was specified, try to use that plate's thumbnail first.
  495. """
  496. thumbnail_paths = []
  497. # If a specific plate was printed, try that thumbnail first
  498. if self.plate_number:
  499. thumbnail_paths.append(f"Metadata/plate_{self.plate_number}.png")
  500. # Fallback to default paths
  501. thumbnail_paths.extend(
  502. [
  503. "Metadata/plate_1.png",
  504. "Metadata/thumbnail.png",
  505. "Metadata/model_thumbnail.png",
  506. # Project-wide thumbnail BambuStudio embeds at upload time. We
  507. # only reach this when BS hasn't written a per-plate
  508. # ``Metadata/plate_N.png`` — most notably the #1493 cross-class
  509. # re-slice path where ``--arrange`` rearranges objects but the
  510. # CLI then doesn't emit a fresh per-plate preview. The
  511. # ``_middle`` size is the editor-quality variant (~500 KB);
  512. # ``_small`` and ``_3mf`` are smaller alternates if it's not
  513. # present. Without this fallback the re-sliced archive cards
  514. # render without a cover image.
  515. "Auxiliaries/.thumbnails/thumbnail_middle.png",
  516. "Auxiliaries/.thumbnails/thumbnail_small.png",
  517. "Auxiliaries/.thumbnails/thumbnail_3mf.png",
  518. ]
  519. )
  520. for thumb_path in thumbnail_paths:
  521. if thumb_path in zf.namelist():
  522. self.metadata["_thumbnail_data"] = zf.read(thumb_path)
  523. self.metadata["_thumbnail_ext"] = ".png"
  524. break
  525. def extract_printable_objects_from_archive(
  526. file_path: Path, plate_number: int | None = None
  527. ) -> tuple[dict[int, dict], list | None]:
  528. """Objects and plate bbox for an archived print, read off local disk.
  529. The archive of a running print usually holds the very 3MF the printer is
  530. executing, so the object list can be rebuilt without asking the printer for
  531. a file we already have -- 15 MB over FTPS from a machine that is mid-print,
  532. in the case this was written for. Returns empty when the archive has
  533. no readable 3MF, which is the caller's signal to fall back to the printer.
  534. """
  535. if not file_path.is_file() or not str(file_path).endswith(".3mf"):
  536. return {}, None
  537. try:
  538. data = file_path.read_bytes()
  539. except OSError:
  540. return {}, None
  541. return extract_printable_objects_from_3mf(data, plate_number=plate_number, include_positions=True)
  542. def extract_printable_objects_from_3mf(
  543. data: bytes, plate_number: int | None = None, include_positions: bool = False
  544. ) -> dict[int, str] | dict[int, dict] | tuple[dict[int, dict], list | None]:
  545. """Extract printable objects from 3MF file bytes.
  546. This is a lightweight function used during print start to get the list
  547. of objects that can be skipped.
  548. Args:
  549. data: Raw bytes of the 3MF file
  550. plate_number: Which plate was printed (1-based), or None for first plate
  551. include_positions: If True, return tuple of (objects dict, bbox_all)
  552. Returns:
  553. If include_positions=False: Dictionary mapping identify_id (int) to object name (str)
  554. If include_positions=True: Tuple of (dict mapping identify_id to {name, x, y}, bbox_all list or None)
  555. """
  556. from io import BytesIO
  557. printable_objects: dict = {}
  558. bbox_all: list | None = None
  559. try:
  560. with zipfile.ZipFile(BytesIO(data), "r") as zf:
  561. if "Metadata/slice_info.config" not in zf.namelist():
  562. return printable_objects
  563. content = zf.read("Metadata/slice_info.config").decode()
  564. root = ET.fromstring(content)
  565. plates = root.findall(".//plate")
  566. if not plates:
  567. return printable_objects
  568. # Pick the plate that is actually printing. An all-plates export
  569. # lists every plate, so without this we offered the objects (and
  570. # the marker positions) of plate 1 whatever the printer was
  571. # running (#2522). Falling back to the first plate keeps the
  572. # single-plate export — the common case — working when the caller
  573. # has no plate to give us.
  574. plate = None
  575. if plate_number is not None:
  576. plate = next((p for p in plates if _read_plate_index(p) == plate_number), None)
  577. if plate is None:
  578. plate = plates[0]
  579. # Derive plate_idx from the plate we settled on, never from the
  580. # requested one: on a fallback they differ, and plate_idx also
  581. # selects the plate_N.json the positions come from.
  582. plate_idx = _read_plate_index(plate) or 1
  583. # Load position data from plate_N.json if we need positions
  584. # Build a lookup by name - use list to handle duplicate names
  585. bbox_by_name: dict[str, list[list]] = {}
  586. if include_positions:
  587. plate_json_path = f"Metadata/plate_{plate_idx}.json"
  588. if plate_json_path in zf.namelist():
  589. try:
  590. plate_json = json.loads(zf.read(plate_json_path).decode())
  591. # Get bbox_all - the bounding box of all objects (used for image bounds)
  592. bbox_all = plate_json.get("bbox_all")
  593. for bbox_obj in plate_json.get("bbox_objects", []):
  594. obj_name = bbox_obj.get("name")
  595. bbox = bbox_obj.get("bbox", [])
  596. if obj_name and len(bbox) >= 4:
  597. if obj_name not in bbox_by_name:
  598. bbox_by_name[obj_name] = []
  599. bbox_by_name[obj_name].append(bbox)
  600. except (json.JSONDecodeError, KeyError):
  601. pass # Position data is optional; objects will lack x/y coordinates
  602. # Extract objects from slice_info.config
  603. for obj in plate.findall("object"):
  604. identify_id = obj.get("identify_id")
  605. name = obj.get("name")
  606. skipped = obj.get("skipped", "false")
  607. if identify_id and name and skipped.lower() != "true":
  608. try:
  609. obj_id = int(identify_id)
  610. if include_positions:
  611. x, y = None, None
  612. # Match by name - pop first bbox to handle duplicates
  613. bboxes = bbox_by_name.get(name)
  614. if bboxes:
  615. bbox = bboxes.pop(0)
  616. # Calculate center from bbox [x_min, y_min, x_max, y_max]
  617. x = (bbox[0] + bbox[2]) / 2
  618. y = (bbox[1] + bbox[3]) / 2
  619. printable_objects[obj_id] = {"name": name, "x": x, "y": y}
  620. else:
  621. printable_objects[obj_id] = name
  622. except ValueError:
  623. pass # Skip objects with non-numeric identify_id
  624. except Exception:
  625. pass # Return empty dict if 3MF is corrupt or unreadable
  626. if include_positions:
  627. return printable_objects, bbox_all
  628. return printable_objects
  629. class ProjectPageParser:
  630. """Parser for extracting project page data from Bambu Lab 3MF files."""
  631. def __init__(self, file_path: Path):
  632. self.file_path = file_path
  633. def parse(self, archive_id: int) -> dict:
  634. """Extract project page metadata and images from 3MF file."""
  635. import html
  636. result = {
  637. "title": None,
  638. "description": None,
  639. "designer": None,
  640. "designer_user_id": None,
  641. "license": None,
  642. "copyright": None,
  643. "creation_date": None,
  644. "modification_date": None,
  645. "origin": None,
  646. "profile_title": None,
  647. "profile_description": None,
  648. "profile_cover": None,
  649. "profile_user_id": None,
  650. "profile_user_name": None,
  651. "design_model_id": None,
  652. "design_profile_id": None,
  653. "design_region": None,
  654. "model_pictures": [],
  655. "profile_pictures": [],
  656. "thumbnails": [],
  657. }
  658. try:
  659. with zipfile.ZipFile(self.file_path, "r") as zf:
  660. # Parse 3D/3dmodel.model for metadata
  661. model_path = "3D/3dmodel.model"
  662. if model_path in zf.namelist():
  663. content = zf.read(model_path).decode("utf-8", errors="ignore")
  664. # Extract metadata elements using regex
  665. # Format: <metadata name="Key">Value</metadata> or <metadata name="Key" />
  666. metadata_pattern = r'<metadata\s+name="([^"]+)"[^>]*>([^<]*)</metadata>'
  667. matches = re.findall(metadata_pattern, content)
  668. field_mapping = {
  669. "Title": "title",
  670. "Description": "description",
  671. "Designer": "designer",
  672. "DesignerUserId": "designer_user_id",
  673. "License": "license",
  674. "Copyright": "copyright",
  675. "CreationDate": "creation_date",
  676. "ModificationDate": "modification_date",
  677. "Origin": "origin",
  678. "ProfileTitle": "profile_title",
  679. "ProfileDescription": "profile_description",
  680. "ProfileCover": "profile_cover",
  681. "ProfileUserId": "profile_user_id",
  682. "ProfileUserName": "profile_user_name",
  683. "DesignModelId": "design_model_id",
  684. "DesignProfileId": "design_profile_id",
  685. "DesignRegion": "design_region",
  686. }
  687. for name, value in matches:
  688. if name in field_mapping:
  689. # Decode HTML entities multiple times (content is often triple-encoded)
  690. decoded = value.strip()
  691. prev = None
  692. while prev != decoded:
  693. prev = decoded
  694. decoded = html.unescape(decoded)
  695. # Normalize non-breaking spaces to regular spaces
  696. decoded = decoded.replace("\xa0", " ")
  697. result[field_mapping[name]] = decoded if decoded else None
  698. # List images in Auxiliaries folder
  699. from urllib.parse import quote
  700. for name in zf.namelist():
  701. if name.startswith("Auxiliaries/Model Pictures/"):
  702. filename = name.split("/")[-1]
  703. if filename:
  704. result["model_pictures"].append(
  705. {
  706. "name": filename,
  707. "path": name,
  708. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  709. }
  710. )
  711. elif name.startswith("Auxiliaries/Profile Pictures/"):
  712. filename = name.split("/")[-1]
  713. if filename:
  714. result["profile_pictures"].append(
  715. {
  716. "name": filename,
  717. "path": name,
  718. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  719. }
  720. )
  721. elif name.startswith("Auxiliaries/.thumbnails/"):
  722. filename = name.split("/")[-1]
  723. if filename:
  724. result["thumbnails"].append(
  725. {
  726. "name": filename,
  727. "path": name,
  728. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  729. }
  730. )
  731. except Exception as e:
  732. result["_error"] = str(e)
  733. return result
  734. def get_image(self, image_path: str) -> tuple[bytes, str] | None:
  735. """Extract an image from the 3MF file.
  736. Returns tuple of (image_data, content_type) or None if not found.
  737. """
  738. try:
  739. with zipfile.ZipFile(self.file_path, "r") as zf:
  740. if image_path in zf.namelist():
  741. data = zf.read(image_path)
  742. # Determine content type from extension
  743. ext = image_path.lower().split(".")[-1]
  744. content_types = {
  745. "png": "image/png",
  746. "jpg": "image/jpeg",
  747. "jpeg": "image/jpeg",
  748. "webp": "image/webp",
  749. "gif": "image/gif",
  750. }
  751. content_type = content_types.get(ext, "application/octet-stream")
  752. return (data, content_type)
  753. except Exception:
  754. pass # Return None if image cannot be extracted from 3MF
  755. return None
  756. def update_metadata(self, updates: dict) -> bool:
  757. """Update project page metadata in the 3MF file.
  758. Args:
  759. updates: Dict with fields to update (title, description, designer, etc.)
  760. Returns:
  761. True if successful, False otherwise.
  762. """
  763. import html
  764. import tempfile
  765. try:
  766. # Read the 3MF file
  767. with zipfile.ZipFile(self.file_path, "r") as zf_read:
  768. # Find and read the 3dmodel.model file
  769. model_path = "3D/3dmodel.model"
  770. if model_path not in zf_read.namelist():
  771. return False
  772. content = zf_read.read(model_path).decode("utf-8")
  773. # Update metadata fields
  774. field_mapping = {
  775. "title": "Title",
  776. "description": "Description",
  777. "designer": "Designer",
  778. "license": "License",
  779. "copyright": "Copyright",
  780. "profile_title": "ProfileTitle",
  781. "profile_description": "ProfileDescription",
  782. }
  783. for field, xml_name in field_mapping.items():
  784. if field in updates and updates[field] is not None:
  785. new_value = html.escape(updates[field])
  786. # Replace existing metadata or we'd need to add it
  787. pattern = rf'(<metadata\s+name="{xml_name}"[^>]*>)[^<]*(</metadata>)'
  788. replacement = rf"\g<1>{new_value}\g<2>"
  789. content = re.sub(pattern, replacement, content)
  790. # Write to a temporary file first
  791. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf") as tmp:
  792. tmp_path = Path(tmp.name)
  793. # Create new zip with updated content
  794. with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as zf_write:
  795. for item in zf_read.namelist():
  796. if item == model_path:
  797. zf_write.writestr(item, content.encode("utf-8"))
  798. else:
  799. zf_write.writestr(item, zf_read.read(item))
  800. # Replace original file with updated one
  801. shutil.move(tmp_path, self.file_path)
  802. return True
  803. except Exception:
  804. # Clean up temp file if it exists
  805. if "tmp_path" in locals() and tmp_path.exists():
  806. tmp_path.unlink()
  807. return False
  808. async def _null_print_log_thumbnail_paths(db: AsyncSession, archive_id: int) -> None:
  809. """NULL thumbnail_path on PrintLogEntry rows linked to *archive_id*.
  810. Called from both soft- and hard-delete paths before the archive's files
  811. leave disk. The FK on PrintLogEntry.archive_id is ON DELETE SET NULL so
  812. log rows survive the archive — without this clear, their cached
  813. thumbnail_path would still point at a deleted file and the print-log
  814. view would 404-storm on every render (#1348 follow-up). Lazy-NULL on
  815. the GET route self-heals stragglers (e.g. failed prints that never had
  816. a thumbnail written), but eager clear here avoids the one-time storm.
  817. """
  818. from sqlalchemy import update as sa_update
  819. from backend.app.models.print_log import PrintLogEntry
  820. await db.execute(sa_update(PrintLogEntry).where(PrintLogEntry.archive_id == archive_id).values(thumbnail_path=None))
  821. async def _delete_related_queue_items(db: AsyncSession, archive_id: int) -> int:
  822. """Delete every queue item pointing at *archive_id* (#1734).
  823. Called from ``soft_delete_archive``. Hard-delete is covered by the
  824. ``ON DELETE CASCADE`` on ``print_queue.archive_id`` — same end state
  825. via the FK. Pre-#1734 this helper merely flipped pending rows to
  826. ``status='cancelled'`` while leaving every other status alone and
  827. leaving the rows in the DB, which surprised users who expected the
  828. queue lines to disappear when their backing archive went away. Worse,
  829. a Send-All archive backed N queue items (one per plate, #1733) — soft-
  830. deleting that archive left N "cancelled" rows behind, none of which
  831. could ever dispatch.
  832. Now we delete unconditionally regardless of status. ``printing`` rows
  833. are blocked one layer up at the route (``delete_archive`` returns 409
  834. when a related row is mid-print) so we never delete an actively-
  835. running queue row out from under the dispatcher. Completed / failed
  836. / cancelled rows go too — they're queue history, not print history.
  837. PrintLogEntry rows are the authoritative print history and are
  838. untouched (FK ``ON DELETE SET NULL``).
  839. Returns the number of rows removed so the caller can report it.
  840. """
  841. from sqlalchemy import delete as sa_delete
  842. from backend.app.models.print_queue import PrintQueueItem
  843. result = await db.execute(sa_delete(PrintQueueItem).where(PrintQueueItem.archive_id == archive_id))
  844. return result.rowcount or 0
  845. async def _count_related_queue_items(db: AsyncSession, archive_id: int) -> tuple[int, int]:
  846. """Return ``(total, printing)`` queue items linked to *archive_id*.
  847. Used by the archive GET response so the frontend delete-confirm modal
  848. can surface how much the deletion will wipe out, and by the delete
  849. route so it can 409 when a related row is currently printing (#1734).
  850. """
  851. from sqlalchemy import func as sa_func, select as sa_select
  852. from backend.app.models.print_queue import PrintQueueItem
  853. total = (
  854. await db.execute(
  855. sa_select(sa_func.count()).select_from(PrintQueueItem).where(PrintQueueItem.archive_id == archive_id)
  856. )
  857. ).scalar_one()
  858. printing = (
  859. await db.execute(
  860. sa_select(sa_func.count())
  861. .select_from(PrintQueueItem)
  862. .where(
  863. PrintQueueItem.archive_id == archive_id,
  864. PrintQueueItem.status == "printing",
  865. )
  866. )
  867. ).scalar_one()
  868. return int(total or 0), int(printing or 0)
  869. class ArchiveService:
  870. """Service for archiving print jobs."""
  871. def __init__(self, db: AsyncSession):
  872. self.db = db
  873. @staticmethod
  874. def compute_file_hash(file_path: Path) -> str:
  875. """Compute SHA256 hash of a file for duplicate detection."""
  876. sha256 = hashlib.sha256()
  877. with open(file_path, "rb") as f:
  878. # Read in chunks to handle large files
  879. for chunk in iter(lambda: f.read(8192), b""):
  880. sha256.update(chunk)
  881. return sha256.hexdigest()
  882. async def get_duplicate_hashes_and_names(self) -> tuple[set[str], set[tuple[str, str]]]:
  883. """Get all content hashes and (print name, hash) pairs that appear more than once.
  884. For hashes: returns all hashes with > 1 archive (true duplicates).
  885. For name/hash pairs: returns only pairs that have > 1 archive
  886. (i.e., same file archived multiple times, not different files with same name).
  887. Returns a tuple of (duplicate_hashes, duplicate_name_hash_pairs).
  888. """
  889. from sqlalchemy import func
  890. # Soft-deleted archives don't appear in the listing (#1343), so they
  891. # mustn't influence the duplicate-group counts either — otherwise a
  892. # group with 1 live + 4 soft-deleted would still be flagged as a
  893. # duplicate even though the user only sees one row.
  894. result = await self.db.execute(
  895. select(PrintArchive.content_hash)
  896. .where(PrintArchive.content_hash.isnot(None), PrintArchive.deleted_at.is_(None))
  897. .group_by(PrintArchive.content_hash)
  898. .having(func.count(PrintArchive.id) > 1)
  899. )
  900. duplicate_hashes = {row[0] for row in result.all()}
  901. # Find print names that have multiple archives with the SAME hash
  902. # This avoids marking different files with the same name as duplicates
  903. result = await self.db.execute(
  904. select(func.lower(PrintArchive.print_name), PrintArchive.content_hash)
  905. .where(
  906. PrintArchive.print_name.isnot(None),
  907. PrintArchive.content_hash.isnot(None),
  908. PrintArchive.deleted_at.is_(None),
  909. )
  910. .group_by(func.lower(PrintArchive.print_name), PrintArchive.content_hash)
  911. .having(func.count(PrintArchive.id) > 1)
  912. )
  913. duplicate_name_hash_pairs = {(row[0], row[1]) for row in result.all()}
  914. return duplicate_hashes, duplicate_name_hash_pairs
  915. async def find_duplicates(
  916. self,
  917. archive_id: int,
  918. content_hash: str | None = None,
  919. print_name: str | None = None,
  920. makerworld_model_id: str | None = None,
  921. ) -> list[dict]:
  922. """Find duplicate archives based on hash or name matching.
  923. Returns list of dicts with id, print_name, created_at, match_type.
  924. """
  925. duplicates = []
  926. # First, find exact matches by content hash
  927. if content_hash:
  928. result = await self.db.execute(
  929. select(PrintArchive)
  930. .where(
  931. and_(
  932. PrintArchive.content_hash == content_hash,
  933. PrintArchive.id != archive_id,
  934. PrintArchive.deleted_at.is_(None),
  935. )
  936. )
  937. .order_by(PrintArchive.created_at.desc())
  938. .limit(10)
  939. )
  940. for archive in result.scalars().all():
  941. duplicates.append(
  942. {
  943. "id": archive.id,
  944. "print_name": archive.print_name,
  945. "created_at": archive.created_at,
  946. "match_type": "exact",
  947. }
  948. )
  949. # Then, find similar matches by print name or MakerWorld ID
  950. # Prefer strict name+hash matching when hash exists; fallback to name-only for legacy/manual
  951. # archives that may not have a content_hash.
  952. if print_name or makerworld_model_id:
  953. conditions = [PrintArchive.id != archive_id, PrintArchive.deleted_at.is_(None)]
  954. name_conditions = []
  955. if print_name:
  956. if content_hash:
  957. # Match if print names are similar AND have the same hash (same file)
  958. name_conditions.append(
  959. and_(PrintArchive.print_name.ilike(print_name), PrintArchive.content_hash == content_hash)
  960. )
  961. else:
  962. # Fallback for archives without hash data: match by print name only.
  963. name_conditions.append(PrintArchive.print_name.ilike(print_name))
  964. if makerworld_model_id:
  965. # Match by MakerWorld model ID stored in extra_data
  966. from backend.app.core.db_dialect import is_sqlite
  967. if is_sqlite():
  968. from sqlalchemy import func
  969. name_conditions.append(
  970. func.json_extract(PrintArchive.extra_data, "$.makerworld_model_id") == str(makerworld_model_id)
  971. )
  972. else:
  973. name_conditions.append(
  974. text("(extra_data::jsonb->>'makerworld_model_id') = :mw_id").bindparams(
  975. mw_id=str(makerworld_model_id)
  976. )
  977. )
  978. if name_conditions:
  979. conditions.append(or_(*name_conditions))
  980. result = await self.db.execute(
  981. select(PrintArchive).where(and_(*conditions)).order_by(PrintArchive.created_at.desc()).limit(10)
  982. )
  983. for archive in result.scalars().all():
  984. # Don't add if already in duplicates (exact match)
  985. if not any(d["id"] == archive.id for d in duplicates):
  986. duplicates.append(
  987. {
  988. "id": archive.id,
  989. "print_name": archive.print_name,
  990. "created_at": archive.created_at,
  991. "match_type": "similar",
  992. }
  993. )
  994. return duplicates
  995. async def archive_print(
  996. self,
  997. printer_id: int | None,
  998. source_file: Path,
  999. print_data: dict | None = None,
  1000. created_by_id: int | None = None,
  1001. original_filename: str | None = None,
  1002. project_id: int | None = None,
  1003. cost_center_id: int | None = None,
  1004. subtask_id: str | None = None,
  1005. prefer_filename_for_name: bool = False,
  1006. plate_id: int | None = None,
  1007. library_file_id: int | None = None,
  1008. slicer_ams_mapping: list[int] | None = None,
  1009. slicer_ams_mapping_printer_id: int | None = None,
  1010. ) -> PrintArchive | None:
  1011. """Archive a 3MF file with metadata.
  1012. Args:
  1013. printer_id: ID of the printer (optional)
  1014. source_file: Path to the 3MF file
  1015. print_data: Print data from MQTT (optional)
  1016. created_by_id: User ID who created this archive (optional, for user tracking)
  1017. original_filename: Original human-readable filename (optional, for library files
  1018. stored with UUID names)
  1019. project_id: Project to associate this archive with (optional, set when triggered
  1020. from the project view)
  1021. library_file_id: Library file this run was dispatched from (optional,
  1022. set by the queue scheduler — powers per-file project progress, #1897)
  1023. subtask_id: MQTT-provided task identifier (optional). Used to match an
  1024. existing archive across a backend restart mid-print so the
  1025. original row can be resumed instead of cancelled (#972).
  1026. prefer_filename_for_name: When True, use the uploaded filename stem as the
  1027. archive's display name even if the 3MF embeds a `print_name` in its
  1028. metadata. Used by virtual-printer flows so users who rename a job in
  1029. BambuStudio's "send to printer" dialog see that name instead of the
  1030. creator-baked title (#1152).
  1031. slicer_ams_mapping: The slicer's own live-resolved AMS-slot pick, to persist
  1032. onto `extra_data.slicer_ams_mapping` for a later reprint to reuse. Deliberately
  1033. a distinct parameter, not read off `print_data["ams_mapping"]` — that key is
  1034. populated on every MQTT print-start callback regardless of source (bambu_mqtt's
  1035. request-topic interception captures it for slicer-direct LAN prints too), so
  1036. promoting it unconditionally would stamp every archive on installs with no
  1037. virtual printer at all. Callers that gate this behind an opt-in (the VP-queue
  1038. "Save AMS mapping" toggle) pass it explicitly; everyone else leaves it unset.
  1039. slicer_ams_mapping_printer_id: The printer `slicer_ams_mapping`'s tray IDs were
  1040. resolved against. Required alongside `slicer_ams_mapping` — a global tray ID
  1041. only means something relative to one printer's specific AMS layout, so a
  1042. mapping saved without knowing which printer it came from can't be safely
  1043. reused later on any printer, including the same one (there'd be no way to
  1044. tell). A model-based VP with no fixed target printer has no valid value to
  1045. pass here and must leave both params unset.
  1046. """
  1047. # Verify printer exists if specified
  1048. if printer_id is not None:
  1049. result = await self.db.execute(select(Printer).where(Printer.id == printer_id))
  1050. printer = result.scalar_one_or_none()
  1051. if not printer:
  1052. return None
  1053. # Create archive directory structure
  1054. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1055. display_stem = resolve_display_stem(original_filename if original_filename else source_file.name)
  1056. archive_name = f"{timestamp}_{display_stem}"
  1057. # Use "unassigned" folder for archives without a printer
  1058. printer_folder = str(printer_id) if printer_id is not None else "unassigned"
  1059. archive_dir = (
  1060. settings.archive_dir / printer_folder / archive_name
  1061. ) # SEC-PATH-OK: printer_folder = str(int|None) → digits or "unassigned"; archive_name = f"{timestamp}_{display_stem}" where resolve_display_stem strips path components via Path(filename).name
  1062. archive_dir.mkdir(parents=True, exist_ok=True)
  1063. # Copy 3MF file with an explicit fsync'd loop (avoids a sendfile
  1064. # short-read quirk that silently truncated 3MF archives on some
  1065. # platforms — see _copy_and_fsync and #1032).
  1066. dest_file = archive_dir / source_file.name
  1067. _copy_and_fsync(source_file, dest_file)
  1068. # If we just archived a 3MF, verify the dest is a valid ZIP before
  1069. # going any further. Staying quiet here is how #1032 escaped review —
  1070. # the archive row was written but every later zipfile.ZipFile() call
  1071. # on the dest failed with "File is not a zip file".
  1072. if (
  1073. source_file.suffix.lower() == ".3mf"
  1074. and zipfile.is_zipfile(source_file)
  1075. and not zipfile.is_zipfile(dest_file)
  1076. ):
  1077. try:
  1078. src_size = source_file.stat().st_size
  1079. dst_size = dest_file.stat().st_size
  1080. except OSError:
  1081. src_size = dst_size = -1
  1082. logger.error(
  1083. "Archive copy corrupted 3MF: src=%s (%s bytes, valid ZIP) -> dst=%s (%s bytes, NOT a ZIP). Refusing to create archive row.",
  1084. source_file,
  1085. src_size,
  1086. dest_file,
  1087. dst_size,
  1088. )
  1089. # Narrow cleanup: remove only the truncated file and the archive
  1090. # directory if it's now empty. archive_dir was created with
  1091. # exist_ok=True so it could in theory pre-date this call (e.g.
  1092. # same-second same-filename collision); rmtree would be too broad.
  1093. try:
  1094. dest_file.unlink()
  1095. except OSError:
  1096. pass
  1097. try:
  1098. archive_dir.rmdir()
  1099. except OSError:
  1100. pass # directory not empty — leave untouched
  1101. return None
  1102. # Compute content hash for duplicate detection
  1103. content_hash = self.compute_file_hash(dest_file)
  1104. # Extract plate number from filename (e.g., "plate_5" from "/data/Metadata/plate_5.gcode")
  1105. plate_number = None
  1106. if print_data:
  1107. filename = print_data.get("filename", "")
  1108. match = re.search(r"plate_(\d+)", filename)
  1109. if match:
  1110. plate_number = int(match.group(1))
  1111. # Parse 3MF metadata
  1112. parser = ThreeMFParser(dest_file, plate_number=plate_number)
  1113. metadata = parser.parse()
  1114. # Save thumbnail if present
  1115. thumbnail_path = None
  1116. if "_thumbnail_data" in metadata:
  1117. thumb_file = archive_dir / f"thumbnail{metadata['_thumbnail_ext']}"
  1118. thumb_file.write_bytes(metadata["_thumbnail_data"])
  1119. thumbnail_path = str(thumb_file.relative_to(settings.base_dir))
  1120. del metadata["_thumbnail_data"]
  1121. del metadata["_thumbnail_ext"]
  1122. # Merge with print data from MQTT
  1123. if print_data:
  1124. metadata["_print_data"] = print_data
  1125. # Promote the slicer's own live-resolved AMS-slot pick, when the caller
  1126. # explicitly opted in (see the `slicer_ams_mapping` param docstring for
  1127. # why this is NOT read off `print_data["ams_mapping"]`), to a stable
  1128. # top-level extra_data key. Lets a later reprint reuse the exact tray
  1129. # the user picked/BambuStudio auto-matched at slice time instead of the
  1130. # scheduler re-deriving one from just the file's static type/color,
  1131. # which can land on the wrong physical spool when that match isn't
  1132. # unique. Top-level (not nested under the `_print_data` diagnostic bag)
  1133. # so API consumers have a single stable path:
  1134. # `archive.extra_data.slicer_ams_mapping`. Stored together with the
  1135. # printer it was resolved against — see `slicer_ams_mapping_printer_id`
  1136. # param docstring — so a later reprint can tell whether it's even
  1137. # applicable before trying to reuse it.
  1138. if slicer_ams_mapping and slicer_ams_mapping_printer_id is not None:
  1139. metadata["slicer_ams_mapping"] = {
  1140. "mapping": slicer_ams_mapping,
  1141. "printer_id": slicer_ams_mapping_printer_id,
  1142. }
  1143. # Determine status and timestamps
  1144. status = print_data.get("status", "completed") if print_data else "archived"
  1145. started_at = datetime.now(timezone.utc) if status == "printing" else None
  1146. completed_at = datetime.now(timezone.utc) if status in ("completed", "failed", "archived") else None
  1147. # Calculate cost based on filament usage and type
  1148. cost = None
  1149. filament_grams = metadata.get("filament_used_grams")
  1150. filament_type = metadata.get("filament_type")
  1151. if filament_grams and filament_type:
  1152. # For multi-material prints, use the first filament type for cost calculation
  1153. primary_type = filament_type.split(",")[0].strip()
  1154. # Look up filament cost_per_kg from database
  1155. filament_result = await self.db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  1156. filament = filament_result.scalar_one_or_none()
  1157. if filament:
  1158. cost = round((filament_grams / 1000) * filament.cost_per_kg, 2)
  1159. else:
  1160. # Use default filament cost from settings
  1161. from backend.app.api.routes.settings import get_setting
  1162. default_cost_setting = await get_setting(self.db, "default_filament_cost")
  1163. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1164. cost = round((filament_grams / 1000) * default_cost_per_kg, 2)
  1165. # Calculate quantity from printable objects count
  1166. # printable_objects is a dict of {identify_id: name} for non-skipped objects
  1167. quantity = 1 # Default to 1
  1168. printable_objects = metadata.get("printable_objects")
  1169. if printable_objects and isinstance(printable_objects, dict):
  1170. quantity = len(printable_objects)
  1171. logger.debug("Auto-detected %s parts from 3MF printable objects", quantity)
  1172. # Create archive record
  1173. archive = PrintArchive(
  1174. printer_id=printer_id,
  1175. filename=original_filename or source_file.name,
  1176. file_path=str(dest_file.relative_to(settings.base_dir)),
  1177. file_size=dest_file.stat().st_size,
  1178. content_hash=content_hash,
  1179. thumbnail_path=thumbnail_path,
  1180. # clean_display_name because the 3MF's own metadata reaches this
  1181. # verbatim, and a control character in it renders nowhere and
  1182. # truncates somewhere (#2832). The schema does the same for names
  1183. # arriving over the API. Cleaned before the fallback rather than
  1184. # after it, so an embedded name that is only whitespace still falls
  1185. # through to the filename instead of leaving the archive nameless.
  1186. print_name=(
  1187. clean_display_name(display_stem)
  1188. if prefer_filename_for_name
  1189. else (clean_display_name(metadata.get("print_name")) or clean_display_name(display_stem))
  1190. ),
  1191. print_time_seconds=metadata.get("print_time_seconds"),
  1192. filament_used_grams=metadata.get("filament_used_grams"),
  1193. filament_type=metadata.get("filament_type"),
  1194. filament_color=metadata.get("filament_color"),
  1195. layer_height=metadata.get("layer_height"),
  1196. total_layers=metadata.get("total_layers"),
  1197. nozzle_diameter=metadata.get("nozzle_diameter"),
  1198. bed_temperature=metadata.get("bed_temperature"),
  1199. bed_type=metadata.get("bed_type"),
  1200. nozzle_temperature=metadata.get("nozzle_temperature"),
  1201. sliced_for_model=metadata.get("sliced_for_model"),
  1202. makerworld_url=metadata.get("makerworld_url"),
  1203. designer=metadata.get("designer"),
  1204. status=status,
  1205. started_at=started_at,
  1206. completed_at=completed_at,
  1207. cost=cost,
  1208. quantity=quantity,
  1209. extra_data=metadata,
  1210. created_by_id=created_by_id,
  1211. project_id=project_id,
  1212. library_file_id=library_file_id,
  1213. cost_center_id=cost_center_id,
  1214. subtask_id=subtask_id,
  1215. plate_id=plate_id,
  1216. )
  1217. self.db.add(archive)
  1218. await self.db.commit()
  1219. await self.db.refresh(archive)
  1220. return archive
  1221. async def get_archive(self, archive_id: int) -> PrintArchive | None:
  1222. """Get an archive by ID with relationships loaded."""
  1223. from sqlalchemy.orm import selectinload
  1224. result = await self.db.execute(
  1225. select(PrintArchive)
  1226. .options(selectinload(PrintArchive.created_by), selectinload(PrintArchive.project))
  1227. .where(PrintArchive.id == archive_id)
  1228. )
  1229. return result.scalar_one_or_none()
  1230. async def update_archive_status(
  1231. self,
  1232. archive_id: int,
  1233. status: str,
  1234. completed_at: datetime | None = None,
  1235. failure_reason: str | None = None,
  1236. ) -> bool:
  1237. """Update the status of an archive."""
  1238. archive = await self.get_archive(archive_id)
  1239. if not archive:
  1240. return False
  1241. archive.status = status
  1242. if completed_at:
  1243. archive.completed_at = completed_at
  1244. if failure_reason:
  1245. archive.failure_reason = failure_reason
  1246. await self.db.commit()
  1247. return True
  1248. async def list_archives(
  1249. self,
  1250. printer_id: int | None = None,
  1251. project_id: int | None = None,
  1252. date_from: date | None = None,
  1253. date_to: date | None = None,
  1254. limit: int = 50,
  1255. offset: int = 0,
  1256. visible_to_user_id: int | None = None,
  1257. ) -> list[PrintArchive]:
  1258. """List archives with optional filtering.
  1259. ``visible_to_user_id`` scopes results to archives that user owns. Used
  1260. when the caller has ARCHIVES_READ_OWN but not ARCHIVES_READ_ALL — pass
  1261. ``None`` to skip the filter (caller has read-all or auth is disabled).
  1262. """
  1263. from sqlalchemy.orm import selectinload
  1264. query = (
  1265. select(PrintArchive)
  1266. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1267. # Hide soft-deleted rows from the listings (#1343). The stats
  1268. # endpoint deliberately does NOT add this filter so deleted
  1269. # archives keep contributing to Quick Stats.
  1270. .where(PrintArchive.deleted_at.is_(None))
  1271. .order_by(PrintArchive.created_at.desc())
  1272. )
  1273. if printer_id:
  1274. query = query.where(PrintArchive.printer_id == printer_id)
  1275. if project_id:
  1276. query = query.where(PrintArchive.project_id == project_id)
  1277. if date_from:
  1278. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  1279. query = query.where(PrintArchive.created_at >= dt_from)
  1280. if date_to:
  1281. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  1282. query = query.where(PrintArchive.created_at <= dt_to)
  1283. if visible_to_user_id is not None:
  1284. query = query.where(PrintArchive.created_by_id == visible_to_user_id)
  1285. query = query.limit(limit).offset(offset)
  1286. result = await self.db.execute(query)
  1287. return list(result.scalars().all())
  1288. async def soft_delete_archive(self, archive_id: int) -> bool:
  1289. """Soft-delete an archive (#1343).
  1290. Removes the archive's files from disk (it disappears from the listings
  1291. and frees the storage) but flips the row's ``deleted_at`` so the stats
  1292. endpoint keeps counting its filament / energy / time / cost. The user
  1293. can opt into a hard delete via the "Also remove from statistics"
  1294. checkbox in the delete dialog — that path calls ``delete_archive``
  1295. instead and removes the row entirely.
  1296. """
  1297. archive = await self.get_archive(archive_id)
  1298. if not archive:
  1299. return False
  1300. if archive.deleted_at is not None:
  1301. # Already soft-deleted; nothing to do. The files were purged on
  1302. # the first soft-delete pass so there is nothing left on disk.
  1303. return True
  1304. dir_to_delete = self._resolve_archive_dir_for_delete(archive)
  1305. await _null_print_log_thumbnail_paths(self.db, archive_id)
  1306. await _delete_related_queue_items(self.db, archive_id)
  1307. archive.deleted_at = datetime.now(timezone.utc)
  1308. await self.db.commit()
  1309. if dir_to_delete:
  1310. shutil.rmtree(dir_to_delete, ignore_errors=True)
  1311. return True
  1312. def _resolve_archive_dir_for_delete(self, archive: PrintArchive) -> Path | None:
  1313. """Return the on-disk directory that backs *archive*, after the same
  1314. two safety checks ``delete_archive`` enforces.
  1315. Extracted so soft-delete and hard-delete share the path-resolution
  1316. rules. Returns ``None`` when nothing should be removed from disk
  1317. (no file_path, path outside archive_dir, or path not deep enough).
  1318. """
  1319. if not archive.file_path or not archive.file_path.strip():
  1320. logger.error(
  1321. f"SECURITY: Refusing to delete files for archive {archive.id} - "
  1322. f"file_path is empty or invalid: '{archive.file_path}'"
  1323. )
  1324. return None
  1325. file_path = settings.base_dir / archive.file_path
  1326. if not file_path.exists():
  1327. return None
  1328. archive_dir = file_path.parent
  1329. try:
  1330. relative_path = archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1331. except ValueError:
  1332. logger.error(
  1333. f"SECURITY: Refusing to delete archive {archive.id} - "
  1334. f"path {archive_dir} is outside archive directory {settings.archive_dir}"
  1335. )
  1336. return None
  1337. if len(relative_path.parts) < 1:
  1338. logger.error(
  1339. f"SECURITY: Refusing to delete archive {archive.id} - "
  1340. f"path {archive_dir} is not deep enough inside archive directory"
  1341. )
  1342. return None
  1343. return archive_dir
  1344. async def delete_archive(self, archive_id: int) -> bool:
  1345. """Delete an archive and its files."""
  1346. archive = await self.get_archive(archive_id)
  1347. if not archive:
  1348. return False
  1349. # Resolve the directory to delete BEFORE committing the DB change
  1350. dir_to_delete: Path | None = None
  1351. if archive.file_path and archive.file_path.strip():
  1352. file_path = settings.base_dir / archive.file_path
  1353. if file_path.exists():
  1354. archive_dir = file_path.parent
  1355. # Safety check 1: archive_dir must be inside archive_dir
  1356. try:
  1357. archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1358. except ValueError:
  1359. logger.error(
  1360. f"SECURITY: Refusing to delete archive {archive_id} - "
  1361. f"path {archive_dir} is outside archive directory {settings.archive_dir}"
  1362. )
  1363. await self.db.delete(archive)
  1364. await self.db.commit()
  1365. return True
  1366. # Safety check 2: archive_dir must be at least 1 level deep inside archive_dir
  1367. try:
  1368. relative_path = archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1369. if len(relative_path.parts) < 1:
  1370. logger.error(
  1371. f"SECURITY: Refusing to delete archive {archive_id} - "
  1372. f"path {archive_dir} is not deep enough inside archive directory"
  1373. )
  1374. await self.db.delete(archive)
  1375. await self.db.commit()
  1376. return True
  1377. except ValueError:
  1378. pass # Already handled above
  1379. dir_to_delete = archive_dir
  1380. else:
  1381. logger.error(
  1382. f"SECURITY: Refusing to delete files for archive {archive_id} - "
  1383. f"file_path is empty or invalid: '{archive.file_path}'"
  1384. )
  1385. # NULL stale thumbnail_path on linked PrintLogEntries before the FK
  1386. # SET-NULL cascade fires. The on-disk file is about to be removed by
  1387. # the rmtree below, so the path on any surviving log entry (archive_id
  1388. # gets SET NULL by the FK) would otherwise point at a missing file
  1389. # and produce 404 storms in the print-log view (#1348-followup).
  1390. await _null_print_log_thumbnail_paths(self.db, archive_id)
  1391. # Delete database record FIRST — if the commit fails (e.g. database locked
  1392. # during concurrent bulk deletes), the files stay on disk and nothing is lost.
  1393. await self.db.delete(archive)
  1394. await self.db.commit()
  1395. # Only delete files AFTER the DB commit succeeds to avoid orphaned records
  1396. if dir_to_delete:
  1397. shutil.rmtree(dir_to_delete, ignore_errors=True)
  1398. return True
  1399. async def attach_timelapse(
  1400. self,
  1401. archive_id: int,
  1402. timelapse_data: bytes,
  1403. filename: str = "timelapse.mp4",
  1404. ) -> bool:
  1405. """Attach a timelapse video to an archive.
  1406. Non-MP4 videos (e.g. AVI from P1S) are saved as-is and a background
  1407. task converts them to MP4 for browser compatibility.
  1408. """
  1409. import asyncio
  1410. archive = await self.get_archive(archive_id)
  1411. if not archive:
  1412. return False
  1413. # Where this archive's files live. Deliberately the shared helper: an
  1414. # archive created without a 3MF has ``file_path == ""``, and deriving the
  1415. # directory here as ``(base_dir / "").parent`` resolved to the parent of
  1416. # base_dir — outside the data directory entirely. In Docker that is /app,
  1417. # so the write failed with EACCES and the timelapse was retried and
  1418. # discarded 25 times; where the parent happens to be writable it
  1419. # succeeded, dropped a stray video next to the install, and then failed
  1420. # anyway on the relative_to() below. Every H2-series and P2S print sent
  1421. # from the slicer takes that path, because the file goes to internal
  1422. # storage and no 3MF can be fetched.
  1423. archive_dir = resolve_archive_dir(archive)
  1424. # Save timelapse - use thread pool to avoid blocking event loop
  1425. # (timelapse files can be 100MB+, sync write blocks for seconds).
  1426. # `filename` ultimately comes from a printer's FTP listing (compromised-
  1427. # printer threat model) or a query param on /archives/{id}/timelapse/select;
  1428. # the safe-join helper rejects ``..`` segments and absolute paths so a
  1429. # crafted name can't escape the archive directory. Use http=False so a
  1430. # service-layer reject surfaces as a return False (matching the existing
  1431. # not-found contract) rather than a 400 raised from inside a background
  1432. # task.
  1433. try:
  1434. timelapse_file = safe_join_under(archive_dir, filename, http=False)
  1435. except PathTraversalError:
  1436. logger.warning(
  1437. "Refusing to attach timelapse with unsafe filename %r to archive %s",
  1438. filename,
  1439. archive_id,
  1440. )
  1441. return False
  1442. # Created only once the name has been vetted, so a rejected filename
  1443. # leaves nothing behind. A no-3MF archive has never had a directory of
  1444. # its own, and the timelapse can be the first thing to want one.
  1445. await asyncio.to_thread(lambda: timelapse_file.parent.mkdir(parents=True, exist_ok=True))
  1446. await asyncio.to_thread(timelapse_file.write_bytes, timelapse_data)
  1447. # Update archive record
  1448. archive.timelapse_path = str(timelapse_file.relative_to(settings.base_dir))
  1449. await self.db.commit()
  1450. # For non-MP4 videos (e.g. AVI from P1S), kick off background conversion
  1451. if not filename.lower().endswith(".mp4"):
  1452. spawn_background_task(
  1453. _convert_timelapse_to_mp4(archive_id, timelapse_file),
  1454. name=f"timelapse-convert-{archive_id}",
  1455. )
  1456. return True
  1457. async def _convert_timelapse_to_mp4(archive_id: int, source_path: Path) -> None:
  1458. """Background task: convert non-MP4 timelapse (e.g. AVI from P1S) to MP4.
  1459. Runs with low CPU priority (-threads 1, nice) so it doesn't starve
  1460. other processes on resource-constrained devices like Raspberry Pi.
  1461. """
  1462. import asyncio
  1463. from backend.app.core.database import async_session
  1464. from backend.app.services.camera import get_ffmpeg_path
  1465. logger = logging.getLogger(__name__)
  1466. ffmpeg = get_ffmpeg_path()
  1467. if not ffmpeg:
  1468. logger.info(
  1469. "FFmpeg not available, skipping timelapse conversion for archive %s (file saved as %s)",
  1470. archive_id,
  1471. source_path.suffix,
  1472. )
  1473. return
  1474. mp4_path = source_path.with_suffix(".mp4")
  1475. try:
  1476. cmd = [
  1477. ffmpeg,
  1478. "-y",
  1479. "-i",
  1480. str(source_path),
  1481. "-c:v",
  1482. "libx264",
  1483. "-preset",
  1484. "fast",
  1485. "-crf",
  1486. "23",
  1487. "-threads",
  1488. "1",
  1489. "-movflags",
  1490. "+faststart",
  1491. str(mp4_path),
  1492. ]
  1493. # Try with nice for lower CPU priority (standard on Linux/macOS)
  1494. try:
  1495. process = await asyncio.create_subprocess_exec(
  1496. "nice",
  1497. "-n",
  1498. "19",
  1499. *cmd,
  1500. stdout=asyncio.subprocess.PIPE,
  1501. stderr=asyncio.subprocess.PIPE,
  1502. )
  1503. except FileNotFoundError:
  1504. # nice not available (e.g. Windows), run without
  1505. process = await asyncio.create_subprocess_exec(
  1506. *cmd,
  1507. stdout=asyncio.subprocess.PIPE,
  1508. stderr=asyncio.subprocess.PIPE,
  1509. )
  1510. _, stderr = await process.communicate()
  1511. if process.returncode != 0:
  1512. logger.warning(
  1513. "Timelapse conversion failed for archive %s: %s",
  1514. archive_id,
  1515. stderr.decode()[-500:],
  1516. )
  1517. if mp4_path.exists():
  1518. mp4_path.unlink()
  1519. return
  1520. # Update DB path to the new MP4 file
  1521. async with async_session() as db:
  1522. from backend.app.models.archive import PrintArchive
  1523. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1524. archive = result.scalar_one_or_none()
  1525. if archive:
  1526. archive.timelapse_path = str(mp4_path.relative_to(settings.base_dir))
  1527. await db.commit()
  1528. # Remove original non-MP4 file
  1529. if source_path.exists():
  1530. source_path.unlink()
  1531. logger.info(
  1532. "Converted timelapse to MP4 for archive %s (%s → %s)",
  1533. archive_id,
  1534. source_path.name,
  1535. mp4_path.name,
  1536. )
  1537. except Exception as e:
  1538. logger.warning("Timelapse conversion error for archive %s: %s", archive_id, e)
  1539. if mp4_path.exists():
  1540. mp4_path.unlink()