archives.py 169 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358
  1. import io
  2. import json
  3. import logging
  4. import re as _re
  5. import zipfile
  6. from collections import defaultdict
  7. from datetime import date, datetime, time, timedelta, timezone
  8. from decimal import ROUND_HALF_UP, Decimal
  9. from pathlib import Path
  10. from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
  11. from fastapi.responses import FileResponse, Response
  12. from sqlalchemy import and_, case, func, or_, select
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from backend.app.core.auth import (
  15. RequireCameraStreamTokenIfAuthEnabled,
  16. RequirePermissionIfAuthEnabled,
  17. require_ownership_permission,
  18. )
  19. from backend.app.core.config import settings
  20. from backend.app.core.database import get_db
  21. from backend.app.core.permissions import Permission
  22. from backend.app.models.archive import PrintArchive
  23. from backend.app.models.filament import Filament
  24. from backend.app.models.spool_usage_history import SpoolUsageHistory
  25. from backend.app.models.user import User
  26. from backend.app.schemas.archive import ArchiveResponse, ArchiveSlim, ArchiveStats, ArchiveUpdate, ReprintRequest
  27. from backend.app.schemas.print_log import PrintLogResponse
  28. from backend.app.schemas.slicer import SliceRequest
  29. from backend.app.services.archive import ArchiveService
  30. from backend.app.utils.http import build_content_disposition
  31. from backend.app.utils.safe_path import safe_join_under
  32. from backend.app.utils.threemf_tools import (
  33. extract_embedded_presets_from_3mf,
  34. extract_nozzle_mapping_from_3mf,
  35. extract_project_filaments_from_3mf,
  36. )
  37. logger = logging.getLogger(__name__)
  38. router = APIRouter(prefix="/archives", tags=["archives"])
  39. def _safe_filename(filename: str) -> str:
  40. """Extract basename from a client-supplied filename, preventing path traversal.
  41. Normalizes backslashes (Windows paths) before extracting so that
  42. '..\\\\..\\\\evil.3mf' is correctly stripped to 'evil.3mf' on Linux.
  43. """
  44. return Path(filename.replace("\\", "/")).name
  45. _TIMELAPSE_FILENAME_TS_RE = _re.compile(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})")
  46. _DEFAULT_TIMELAPSE_OFFSETS_HOURS: tuple[int, ...] = (0, 8, -8, 7, -7, 1, -1)
  47. _DEFAULT_TIMELAPSE_TOLERANCE = timedelta(hours=4)
  48. _DEFAULT_TIMELAPSE_AMBIGUITY_MARGIN = timedelta(minutes=15)
  49. def _match_timelapse_by_timestamp(
  50. video_files: list[dict],
  51. archive_start: datetime | None,
  52. *,
  53. tolerance: timedelta = _DEFAULT_TIMELAPSE_TOLERANCE,
  54. ambiguity_margin: timedelta = _DEFAULT_TIMELAPSE_AMBIGUITY_MARGIN,
  55. offsets_hours: tuple[int, ...] = _DEFAULT_TIMELAPSE_OFFSETS_HOURS,
  56. ) -> tuple[dict | None, timedelta | None]:
  57. """Pick the timelapse whose filename timestamp best matches the print start time.
  58. Bambu timelapse filenames embed the printer-local START time (e.g.
  59. "video_2026-05-08_09-41-29.mp4"). The printer's clock may be offset from the
  60. server's — especially in LAN-Only mode where NTP is unreachable — so we try a
  61. small set of common UTC offsets and keep the (video, offset) pair with the
  62. smallest absolute distance from archive_start. We deliberately do NOT consider
  63. archive_end here: the filename is start time, not end time, so comparing it to
  64. completion is not a real signal (Strategy 3 handles end via file mtime).
  65. Because the offset list densely covers a wide span, an unrelated video's
  66. filename can coincidentally land near a later print's start at some offset.
  67. To avoid that false positive, we require the best (video, offset) pair to
  68. beat the next-best pair *from a different video* by at least `ambiguity_margin`.
  69. When the top two candidates from different videos are too close to call,
  70. we return None and let the caller fall back to manual selection.
  71. """
  72. if archive_start is None:
  73. return None, None
  74. # (diff, video) for every (video, offset) pair within tolerance.
  75. candidates: list[tuple[timedelta, dict]] = []
  76. for f in video_files:
  77. fname = f.get("name", "")
  78. m = _TIMELAPSE_FILENAME_TS_RE.search(fname)
  79. if not m:
  80. continue
  81. try:
  82. file_time = datetime.strptime(m.group(1), "%Y-%m-%d_%H-%M-%S")
  83. except ValueError:
  84. continue
  85. for hour_offset in offsets_hours:
  86. adjusted = file_time - timedelta(hours=hour_offset)
  87. diff = abs(adjusted - archive_start)
  88. if diff <= tolerance:
  89. candidates.append((diff, f))
  90. if not candidates:
  91. return None, None
  92. candidates.sort(key=lambda c: c[0])
  93. best_diff, best_video = candidates[0]
  94. best_name = best_video.get("name")
  95. for diff, video in candidates[1:]:
  96. if video.get("name") != best_name and (diff - best_diff) < ambiguity_margin:
  97. # Another video matches almost as well — refuse to auto-pick.
  98. return None, None
  99. return best_video, best_diff
  100. def _validate_user_filter_permission(current_user: User | None, created_by_id: int | None):
  101. """Raise 403 if created_by_id filter is used without stats:filter_by_user permission."""
  102. if created_by_id is None or current_user is None:
  103. return
  104. if current_user.is_admin:
  105. return
  106. if not current_user.has_permission(Permission.STATS_FILTER_BY_USER.value):
  107. raise HTTPException(status_code=403, detail="Permission stats:filter_by_user required")
  108. def _apply_user_filter(conditions: list, created_by_id: int | None):
  109. """Append created_by_id filter to conditions list if specified."""
  110. if created_by_id is not None:
  111. if created_by_id == -1:
  112. conditions.append(PrintArchive.created_by_id.is_(None))
  113. else:
  114. conditions.append(PrintArchive.created_by_id == created_by_id)
  115. def _apply_run_user_filter(conditions: list, created_by_id: int | None):
  116. """Append created_by_id filter scoped to PrintLogEntry rows."""
  117. from backend.app.models.print_log import PrintLogEntry
  118. if created_by_id is not None:
  119. if created_by_id == -1:
  120. conditions.append(PrintLogEntry.created_by_id.is_(None))
  121. else:
  122. conditions.append(PrintLogEntry.created_by_id == created_by_id)
  123. def compute_time_accuracy(archive: PrintArchive) -> dict:
  124. """Compute actual print time and accuracy for an archive.
  125. Returns dict with actual_time_seconds and time_accuracy.
  126. time_accuracy = (estimated / actual) * 100
  127. - 100% = perfect estimate
  128. - >100% = print was faster than estimated
  129. - <100% = print took longer than estimated
  130. """
  131. result = {"actual_time_seconds": None, "time_accuracy": None}
  132. if archive.started_at and archive.completed_at and archive.status == "completed":
  133. actual_seconds = int((archive.completed_at - archive.started_at).total_seconds())
  134. if actual_seconds > 0:
  135. result["actual_time_seconds"] = actual_seconds
  136. if archive.print_time_seconds and archive.print_time_seconds > 0:
  137. # Calculate accuracy as percentage
  138. accuracy = (archive.print_time_seconds / actual_seconds) * 100
  139. # Sanity check: skip unreasonable values (e.g., manually changed status)
  140. # Valid range: 5% to 500% (print took 20x longer to 5x faster than estimated)
  141. if 5 <= accuracy <= 500:
  142. result["time_accuracy"] = round(accuracy, 1)
  143. return result
  144. async def _load_run_aggregates(db: AsyncSession, archive_ids: list[int]) -> dict[int, dict]:
  145. """Batch-load per-archive run aggregates from PrintLogEntry.
  146. Returns ``{archive_id: {run_count, last_run_at, total_filament_actual_grams,
  147. successful_run_count, failed_run_count}}``. Archives with no logged runs are
  148. absent from the map; callers should treat that as zero/none.
  149. """
  150. from backend.app.models.print_log import PrintLogEntry
  151. if not archive_ids:
  152. return {}
  153. rows = await db.execute(
  154. select(
  155. PrintLogEntry.archive_id,
  156. func.count(PrintLogEntry.id).label("run_count"),
  157. func.max(PrintLogEntry.started_at).label("last_run_at"),
  158. func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0).label("total_filament"),
  159. func.sum(case((PrintLogEntry.status == "completed", 1), else_=0)).label("successful"),
  160. func.sum(case((PrintLogEntry.status == "failed", 1), else_=0)).label("failed"),
  161. )
  162. .where(PrintLogEntry.archive_id.in_(archive_ids))
  163. .group_by(PrintLogEntry.archive_id)
  164. )
  165. aggregates: dict[int, dict] = {}
  166. for archive_id, run_count, last_run_at, total_filament, successful, failed in rows.all():
  167. aggregates[archive_id] = {
  168. "run_count": int(run_count or 0),
  169. "last_run_at": last_run_at,
  170. "total_filament_actual_grams": float(total_filament) if total_filament else None,
  171. "successful_run_count": int(successful or 0),
  172. "failed_run_count": int(failed or 0),
  173. }
  174. return aggregates
  175. def archive_to_response(
  176. archive: PrintArchive,
  177. duplicates: list[dict] | None = None,
  178. duplicate_count: int = 0,
  179. duplicate_sequence: int = 0,
  180. original_archive_id: int | None = None,
  181. run_aggregate: dict | None = None,
  182. ) -> dict:
  183. """Convert archive model to response dict with computed fields."""
  184. data = {
  185. "id": archive.id,
  186. "printer_id": archive.printer_id,
  187. "project_id": archive.project_id,
  188. "project_name": archive.project.name if archive.project else None,
  189. "filename": archive.filename,
  190. "file_path": archive.file_path,
  191. "file_size": archive.file_size,
  192. "content_hash": archive.content_hash,
  193. "thumbnail_path": archive.thumbnail_path,
  194. "timelapse_path": archive.timelapse_path,
  195. "source_3mf_path": archive.source_3mf_path,
  196. "f3d_path": archive.f3d_path,
  197. "duplicates": duplicates,
  198. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  199. "duplicate_sequence": duplicate_sequence,
  200. "original_archive_id": original_archive_id,
  201. "print_name": archive.print_name,
  202. "print_time_seconds": archive.print_time_seconds,
  203. "filament_used_grams": archive.filament_used_grams,
  204. "filament_type": archive.filament_type,
  205. "filament_color": archive.filament_color,
  206. "layer_height": archive.layer_height,
  207. "total_layers": archive.total_layers,
  208. "nozzle_diameter": archive.nozzle_diameter,
  209. "bed_temperature": archive.bed_temperature,
  210. "bed_type": archive.bed_type,
  211. "nozzle_temperature": archive.nozzle_temperature,
  212. "sliced_for_model": archive.sliced_for_model,
  213. "status": archive.status,
  214. "started_at": archive.started_at,
  215. "completed_at": archive.completed_at,
  216. "extra_data": archive.extra_data,
  217. "makerworld_url": archive.makerworld_url,
  218. "designer": archive.designer,
  219. "external_url": archive.external_url,
  220. "is_favorite": archive.is_favorite,
  221. "tags": archive.tags,
  222. "notes": archive.notes,
  223. "cost": archive.cost,
  224. "photos": archive.photos,
  225. "failure_reason": archive.failure_reason,
  226. "quantity": archive.quantity,
  227. "energy_kwh": archive.energy_kwh,
  228. "energy_cost": archive.energy_cost,
  229. "created_at": archive.created_at,
  230. # User tracking (Issue #206)
  231. "created_by_id": archive.created_by_id,
  232. "created_by_username": archive.created_by.username if archive.created_by else None,
  233. }
  234. # Add computed time accuracy fields
  235. accuracy_data = compute_time_accuracy(archive)
  236. data.update(accuracy_data)
  237. if run_aggregate:
  238. data["run_count"] = run_aggregate.get("run_count", 0)
  239. data["last_run_at"] = run_aggregate.get("last_run_at")
  240. data["total_filament_actual_grams"] = run_aggregate.get("total_filament_actual_grams")
  241. data["successful_run_count"] = run_aggregate.get("successful_run_count", 0)
  242. data["failed_run_count"] = run_aggregate.get("failed_run_count", 0)
  243. return data
  244. @router.get("/", response_model=list[ArchiveResponse])
  245. async def list_archives(
  246. printer_id: int | None = None,
  247. project_id: int | None = None,
  248. date_from: date | None = Query(None),
  249. date_to: date | None = Query(None),
  250. limit: int = 50,
  251. offset: int = 0,
  252. db: AsyncSession = Depends(get_db),
  253. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  254. ):
  255. """List archived prints."""
  256. service = ArchiveService(db)
  257. archives = await service.list_archives(
  258. printer_id=printer_id,
  259. project_id=project_id,
  260. date_from=date_from,
  261. date_to=date_to,
  262. limit=limit,
  263. offset=offset,
  264. )
  265. # Get sets of duplicate hashes and duplicate (name, hash) pairs (efficient single queries)
  266. duplicate_hashes, duplicate_name_hash_pairs = await service.get_duplicate_hashes_and_names()
  267. # Batch-load duplicate groups once for the current page keys.
  268. duplicate_hashes_in_page = {
  269. a.content_hash for a in archives if a.content_hash and a.content_hash in duplicate_hashes
  270. }
  271. duplicate_name_hash_keys_in_page = {
  272. (a.print_name.lower(), a.content_hash)
  273. for a in archives
  274. if a.print_name and a.content_hash and (a.print_name.lower(), a.content_hash) in duplicate_name_hash_pairs
  275. }
  276. duplicate_meta_by_archive_id: dict[int, tuple[int, int, int]] = {}
  277. if duplicate_hashes_in_page or duplicate_name_hash_keys_in_page:
  278. duplicate_group_conditions = []
  279. if duplicate_hashes_in_page:
  280. duplicate_group_conditions.append(PrintArchive.content_hash.in_(duplicate_hashes_in_page))
  281. if duplicate_name_hash_keys_in_page:
  282. name_hash_conditions = [
  283. and_(func.lower(PrintArchive.print_name) == name, PrintArchive.content_hash == hash_)
  284. for name, hash_ in duplicate_name_hash_keys_in_page
  285. ]
  286. duplicate_group_conditions.extend(name_hash_conditions)
  287. duplicate_group_rows = await db.execute(
  288. select(
  289. PrintArchive.id,
  290. PrintArchive.created_at,
  291. PrintArchive.content_hash,
  292. func.lower(PrintArchive.print_name).label("print_name_lower"),
  293. ).where(or_(*duplicate_group_conditions), PrintArchive.deleted_at.is_(None))
  294. )
  295. duplicate_groups_by_hash: dict[str, list[tuple[int, datetime]]] = defaultdict(list)
  296. duplicate_groups_by_name_hash: dict[tuple[str, str], list[tuple[int, datetime]]] = defaultdict(list)
  297. for archive_id, created_at, content_hash, print_name_lower in duplicate_group_rows.all():
  298. if content_hash and content_hash in duplicate_hashes_in_page:
  299. duplicate_groups_by_hash[content_hash].append((archive_id, created_at))
  300. if (
  301. print_name_lower
  302. and content_hash
  303. and (print_name_lower, content_hash) in duplicate_name_hash_keys_in_page
  304. ):
  305. duplicate_groups_by_name_hash[(print_name_lower, content_hash)].append((archive_id, created_at))
  306. for group in duplicate_groups_by_hash.values():
  307. if len(group) < 2:
  308. continue
  309. group.sort(key=lambda x: x[1])
  310. original_id = group[0][0]
  311. duplicate_count = len(group) - 1
  312. for sequence, (archive_id, _) in enumerate(group):
  313. duplicate_meta_by_archive_id[archive_id] = (sequence, original_id, duplicate_count)
  314. # Keep hash-based grouping precedence; name/hash groups only fill missing items.
  315. for group in duplicate_groups_by_name_hash.values():
  316. if len(group) < 2:
  317. continue
  318. group.sort(key=lambda x: x[1])
  319. original_id = group[0][0]
  320. duplicate_count = len(group) - 1
  321. for sequence, (archive_id, _) in enumerate(group):
  322. duplicate_meta_by_archive_id.setdefault(archive_id, (sequence, original_id, duplicate_count))
  323. run_aggregates = await _load_run_aggregates(db, [a.id for a in archives])
  324. # Build response with duplicate sequence and original archive ID pre-computed
  325. result = []
  326. for a in archives:
  327. has_hash_dup = a.content_hash in duplicate_hashes if a.content_hash else False
  328. has_name_dup = (
  329. bool(a.print_name and a.content_hash)
  330. and (a.print_name.lower(), a.content_hash) in duplicate_name_hash_pairs
  331. )
  332. has_duplicate = has_hash_dup or has_name_dup
  333. # Pre-compute duplicate sequence and original archive ID
  334. duplicate_sequence = 0
  335. original_archive_id: int | None = None
  336. duplicate_count = 1 if has_duplicate else 0
  337. if has_duplicate and a.id in duplicate_meta_by_archive_id:
  338. duplicate_sequence, original_archive_id, duplicate_count = duplicate_meta_by_archive_id[a.id]
  339. result.append(
  340. archive_to_response(
  341. a,
  342. duplicate_count=duplicate_count,
  343. duplicate_sequence=duplicate_sequence,
  344. original_archive_id=original_archive_id,
  345. run_aggregate=run_aggregates.get(a.id),
  346. )
  347. )
  348. return result
  349. @router.get("/slim", response_model=list[ArchiveSlim])
  350. async def list_archives_slim(
  351. date_from: date | None = Query(None),
  352. date_to: date | None = Query(None),
  353. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  354. limit: int = Query(default=10000, le=50000),
  355. offset: int = 0,
  356. db: AsyncSession = Depends(get_db),
  357. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  358. ):
  359. """Per-event listing for stats/dashboard widgets.
  360. Reads from print_log_entries so reprints contribute each run and
  361. orphaned events (archive deleted, log row survived via ON DELETE
  362. SET NULL) still aggregate consistently with Quick Stats. The sliced
  363. print_time_seconds is joined from the archive when available; for
  364. orphan events it is null and downstream widgets fall back to the
  365. measured duration_seconds.
  366. """
  367. from backend.app.models.print_log import PrintLogEntry
  368. _validate_user_filter_permission(current_user, created_by_id)
  369. filters = []
  370. if date_from:
  371. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  372. filters.append(PrintLogEntry.created_at >= dt_from)
  373. if date_to:
  374. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  375. filters.append(PrintLogEntry.created_at <= dt_to)
  376. _apply_run_user_filter(filters, created_by_id)
  377. query = (
  378. select(
  379. PrintLogEntry.printer_id,
  380. PrintLogEntry.print_name,
  381. PrintArchive.print_time_seconds,
  382. PrintLogEntry.started_at,
  383. PrintLogEntry.completed_at,
  384. PrintLogEntry.duration_seconds,
  385. PrintLogEntry.filament_used_grams,
  386. PrintLogEntry.filament_type,
  387. PrintLogEntry.filament_color,
  388. PrintLogEntry.status,
  389. PrintLogEntry.cost,
  390. PrintLogEntry.created_at,
  391. )
  392. .outerjoin(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  393. .where(*filters)
  394. .order_by(PrintLogEntry.created_at.desc())
  395. .limit(limit)
  396. .offset(offset)
  397. )
  398. result = await db.execute(query)
  399. rows = result.all()
  400. return [
  401. {
  402. "printer_id": r.printer_id,
  403. "print_name": r.print_name,
  404. "print_time_seconds": r.print_time_seconds,
  405. "actual_time_seconds": (
  406. # Measured elapsed time for every status (#1390): failed /
  407. # cancelled prints still ran for some duration, and Quick
  408. # Stats already counts that. Widgets that fall back to
  409. # print_time_seconds (slicer estimate) for non-completed
  410. # events would diverge from Quick Stats — so expose the
  411. # measured value here unconditionally.
  412. r.duration_seconds
  413. if r.duration_seconds and r.duration_seconds > 0
  414. else (
  415. int((r.completed_at - r.started_at).total_seconds())
  416. if r.started_at and r.completed_at and (r.completed_at - r.started_at).total_seconds() > 0
  417. else None
  418. )
  419. ),
  420. "filament_used_grams": r.filament_used_grams,
  421. "filament_type": r.filament_type,
  422. "filament_color": r.filament_color,
  423. "status": r.status,
  424. "started_at": r.started_at,
  425. "completed_at": r.completed_at,
  426. "cost": r.cost,
  427. "quantity": 1,
  428. "created_at": r.created_at,
  429. }
  430. for r in rows
  431. ]
  432. @router.get("/search", response_model=list[ArchiveResponse])
  433. async def search_archives(
  434. q: str = Query(..., min_length=2, description="Search query"),
  435. printer_id: int | None = None,
  436. project_id: int | None = None,
  437. status: str | None = None,
  438. limit: int = 50,
  439. offset: int = 0,
  440. db: AsyncSession = Depends(get_db),
  441. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  442. ):
  443. """Full-text search across archives.
  444. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  445. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  446. """
  447. from sqlalchemy import text
  448. from sqlalchemy.orm import selectinload
  449. from backend.app.core.db_dialect import is_sqlite
  450. search_term = q.strip()
  451. # Build dialect-specific full-text search query
  452. if is_sqlite():
  453. # SQLite FTS5: wildcard suffix for partial matches
  454. if not search_term.endswith("*"):
  455. search_term = f"{search_term}*"
  456. fts_query = text("""
  457. SELECT rowid FROM archive_fts
  458. WHERE archive_fts MATCH :search_term
  459. ORDER BY rank
  460. LIMIT :limit OFFSET :offset
  461. """)
  462. else:
  463. # PostgreSQL: tsvector + plainto_tsquery with prefix matching
  464. fts_query = text("""
  465. SELECT id FROM print_archives
  466. WHERE to_tsvector('simple',
  467. COALESCE(print_name, '') || ' ' ||
  468. COALESCE(filename, '') || ' ' ||
  469. COALESCE(tags, '') || ' ' ||
  470. COALESCE(notes, '') || ' ' ||
  471. COALESCE(designer, '') || ' ' ||
  472. COALESCE(filament_type, '')
  473. ) @@ to_tsquery('simple', :search_term)
  474. LIMIT :limit OFFSET :offset
  475. """)
  476. # Convert "benchy" to "benchy:*" for prefix matching in tsquery
  477. search_term = " & ".join(f"{word}:*" for word in search_term.split() if word)
  478. try:
  479. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  480. matched_ids = [row[0] for row in result.fetchall()]
  481. except Exception as e:
  482. logger.warning("FTS search failed, falling back to LIKE search: %s", e)
  483. # Fallback to LIKE search if FTS fails
  484. like_pattern = f"%{q}%"
  485. query = (
  486. select(PrintArchive)
  487. .options(selectinload(PrintArchive.project))
  488. .where(
  489. (
  490. (PrintArchive.print_name.ilike(like_pattern))
  491. | (PrintArchive.filename.ilike(like_pattern))
  492. | (PrintArchive.tags.ilike(like_pattern))
  493. | (PrintArchive.notes.ilike(like_pattern))
  494. | (PrintArchive.designer.ilike(like_pattern))
  495. | (PrintArchive.filament_type.ilike(like_pattern))
  496. ),
  497. PrintArchive.deleted_at.is_(None),
  498. )
  499. .order_by(PrintArchive.created_at.desc())
  500. )
  501. if printer_id:
  502. query = query.where(PrintArchive.printer_id == printer_id)
  503. if project_id:
  504. query = query.where(PrintArchive.project_id == project_id)
  505. if status:
  506. query = query.where(PrintArchive.status == status)
  507. query = query.limit(limit).offset(offset)
  508. result = await db.execute(query)
  509. archives = result.scalars().all()
  510. return [archive_to_response(a) for a in archives]
  511. if not matched_ids:
  512. return []
  513. # Fetch full archive records for matched IDs (excluding soft-deleted, #1343)
  514. query = (
  515. select(PrintArchive)
  516. .options(selectinload(PrintArchive.project))
  517. .where(PrintArchive.id.in_(matched_ids), PrintArchive.deleted_at.is_(None))
  518. )
  519. # Apply additional filters
  520. if printer_id:
  521. query = query.where(PrintArchive.printer_id == printer_id)
  522. if project_id:
  523. query = query.where(PrintArchive.project_id == project_id)
  524. if status:
  525. query = query.where(PrintArchive.status == status)
  526. result = await db.execute(query)
  527. archives_dict = {a.id: a for a in result.scalars().all()}
  528. # Preserve FTS ranking order and apply pagination
  529. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  530. paginated = ordered_archives[offset : offset + limit]
  531. return [archive_to_response(a) for a in paginated]
  532. @router.post("/search/rebuild-index")
  533. async def rebuild_search_index(
  534. db: AsyncSession = Depends(get_db),
  535. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  536. ):
  537. """Rebuild the full-text search index from existing archives.
  538. Use this if search results seem incomplete or incorrect.
  539. """
  540. from sqlalchemy import text
  541. from backend.app.core.db_dialect import is_sqlite
  542. try:
  543. if is_sqlite():
  544. # SQLite: rebuild FTS5 virtual table
  545. await db.execute(text("DELETE FROM archive_fts"))
  546. await db.execute(
  547. text("""
  548. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  549. SELECT id, print_name, filename, tags, notes, designer, filament_type
  550. FROM print_archives
  551. """)
  552. )
  553. await db.commit()
  554. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  555. count = result.scalar() or 0
  556. else:
  557. # PostgreSQL: GIN index is auto-maintained, just reindex
  558. await db.execute(text("REINDEX INDEX idx_archives_fulltext"))
  559. await db.commit()
  560. result = await db.execute(text("SELECT COUNT(*) FROM print_archives"))
  561. count = result.scalar() or 0
  562. return {"message": f"Search index rebuilt with {count} entries"}
  563. except Exception as e:
  564. logger.error("Failed to rebuild search index: %s", e)
  565. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  566. @router.get("/analysis/failures")
  567. async def analyze_failures(
  568. days: int | None = None,
  569. date_from: date | None = Query(None),
  570. date_to: date | None = Query(None),
  571. printer_id: int | None = None,
  572. project_id: int | None = None,
  573. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  574. db: AsyncSession = Depends(get_db),
  575. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  576. ):
  577. """Analyze failure patterns across prints.
  578. Returns failure statistics including:
  579. - Overall failure rate
  580. - Failures by reason, filament type, printer
  581. - Time of day distribution
  582. - Recent failures
  583. - Weekly trend
  584. """
  585. _validate_user_filter_permission(current_user, created_by_id)
  586. from backend.app.services.failure_analysis import FailureAnalysisService
  587. service = FailureAnalysisService(db)
  588. return await service.analyze_failures(
  589. days=days,
  590. date_from=date_from,
  591. date_to=date_to,
  592. printer_id=printer_id,
  593. project_id=project_id,
  594. created_by_id=created_by_id,
  595. )
  596. @router.get("/compare")
  597. async def compare_archives(
  598. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  599. db: AsyncSession = Depends(get_db),
  600. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  601. ):
  602. """Compare multiple archives side by side.
  603. Compares print settings, filament usage, and print times.
  604. Also analyzes correlation between settings and success/failure.
  605. Args:
  606. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  607. """
  608. from backend.app.services.archive_comparison import ArchiveComparisonService
  609. # Parse and validate archive IDs
  610. try:
  611. ids = [int(id.strip()) for id in archive_ids.split(",")]
  612. except ValueError:
  613. raise HTTPException(400, "Invalid archive IDs format")
  614. if len(ids) < 2:
  615. raise HTTPException(400, "At least 2 archives required for comparison")
  616. if len(ids) > 5:
  617. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  618. service = ArchiveComparisonService(db)
  619. try:
  620. return await service.compare_archives(ids)
  621. except ValueError as e:
  622. raise HTTPException(400, str(e))
  623. @router.get("/export")
  624. async def export_archives(
  625. format: str = Query("csv", description="Export format: csv or xlsx"),
  626. fields: str | None = Query(None, description="Comma-separated field names"),
  627. printer_id: int | None = None,
  628. project_id: int | None = None,
  629. status: str | None = None,
  630. date_from: str | None = Query(None, description="Start date (ISO format)"),
  631. date_to: str | None = Query(None, description="End date (ISO format)"),
  632. search: str | None = None,
  633. db: AsyncSession = Depends(get_db),
  634. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  635. ):
  636. """Export archives to CSV or Excel format.
  637. Returns a downloadable file with archive data.
  638. """
  639. from datetime import datetime
  640. from fastapi.responses import StreamingResponse
  641. from backend.app.services.export import ExportService
  642. if format not in ("csv", "xlsx"):
  643. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  644. # Parse fields
  645. field_list = None
  646. if fields:
  647. field_list = [f.strip() for f in fields.split(",")]
  648. # Parse dates
  649. date_from_dt = None
  650. date_to_dt = None
  651. if date_from:
  652. try:
  653. date_from_dt = datetime.fromisoformat(date_from)
  654. except ValueError:
  655. raise HTTPException(400, "Invalid date_from format")
  656. if date_to:
  657. try:
  658. date_to_dt = datetime.fromisoformat(date_to)
  659. except ValueError:
  660. raise HTTPException(400, "Invalid date_to format")
  661. service = ExportService(db)
  662. try:
  663. file_bytes, filename, content_type = await service.export_archives(
  664. format=format,
  665. fields=field_list,
  666. printer_id=printer_id,
  667. project_id=project_id,
  668. status=status,
  669. date_from=date_from_dt,
  670. date_to=date_to_dt,
  671. search=search,
  672. )
  673. except ImportError as e:
  674. raise HTTPException(500, str(e))
  675. return StreamingResponse(
  676. io.BytesIO(file_bytes),
  677. media_type=content_type,
  678. headers={"Content-Disposition": build_content_disposition(filename)},
  679. )
  680. @router.get("/stats/export")
  681. async def export_stats(
  682. format: str = Query("csv", description="Export format: csv or xlsx"),
  683. days: int = 30,
  684. printer_id: int | None = None,
  685. project_id: int | None = None,
  686. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  687. db: AsyncSession = Depends(get_db),
  688. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.STATS_READ),
  689. ):
  690. """Export statistics summary to CSV or Excel format."""
  691. _validate_user_filter_permission(current_user, created_by_id)
  692. from fastapi.responses import StreamingResponse
  693. from backend.app.services.export import ExportService
  694. if format not in ("csv", "xlsx"):
  695. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  696. service = ExportService(db)
  697. try:
  698. file_bytes, filename, content_type = await service.export_stats(
  699. format=format,
  700. days=days,
  701. printer_id=printer_id,
  702. project_id=project_id,
  703. created_by_id=created_by_id,
  704. )
  705. except ImportError as e:
  706. raise HTTPException(500, str(e))
  707. return StreamingResponse(
  708. io.BytesIO(file_bytes),
  709. media_type=content_type,
  710. headers={"Content-Disposition": build_content_disposition(filename)},
  711. )
  712. @router.get("/stats", response_model=ArchiveStats)
  713. async def get_archive_stats(
  714. date_from: date | None = Query(None, description="Start date (inclusive), YYYY-MM-DD"),
  715. date_to: date | None = Query(None, description="End date (inclusive), YYYY-MM-DD"),
  716. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  717. db: AsyncSession = Depends(get_db),
  718. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.STATS_READ),
  719. ):
  720. """Get statistics across all archives.
  721. Stats aggregate over PrintLogEntry (one row per print event), not over
  722. PrintArchive (one row per file). A reprint contributes a new PrintLogEntry
  723. so its filament/cost/time/energy add to the totals instead of overwriting
  724. the source archive's first-run values (#1378).
  725. """
  726. from backend.app.models.print_log import PrintLogEntry
  727. _validate_user_filter_permission(current_user, created_by_id)
  728. # Build date filter conditions scoped to PrintLogEntry (event-time).
  729. base_conditions = []
  730. if date_from:
  731. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  732. base_conditions.append(PrintLogEntry.created_at >= dt_from)
  733. if date_to:
  734. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  735. base_conditions.append(PrintLogEntry.created_at <= dt_to)
  736. _apply_run_user_filter(base_conditions, created_by_id)
  737. # Total counts (one row per print event).
  738. total_result = await db.execute(select(func.count(PrintLogEntry.id)).where(*base_conditions))
  739. total_prints = total_result.scalar() or 0
  740. successful_result = await db.execute(
  741. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.status == "completed", *base_conditions)
  742. )
  743. successful_prints = successful_result.scalar() or 0
  744. failed_result = await db.execute(
  745. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.status.in_(("failed", "aborted")), *base_conditions)
  746. )
  747. failed_prints = failed_result.scalar() or 0
  748. # User/system-stopped prints — stopped/cancelled/skipped are distinct from
  749. # quality failures: the user (or the queue) interrupted them, the printer
  750. # didn't detect a fault. Bucketed separately so the Success Rate gauge
  751. # divides by completed + failed only (a cancelled print shouldn't drag
  752. # the gauge down), while still being visible in the breakdown so they
  753. # don't silently vanish from Total Prints (#1390).
  754. cancelled_result = await db.execute(
  755. select(func.count(PrintLogEntry.id)).where(
  756. PrintLogEntry.status.in_(("stopped", "cancelled", "skipped")), *base_conditions
  757. )
  758. )
  759. cancelled_prints = cancelled_result.scalar() or 0
  760. # Total elapsed time — PrintLogEntry stores duration_seconds directly so we
  761. # can sum it server-side. Rows missing duration fall back to the slicer
  762. # estimate from the archive (joined for that case only).
  763. time_rows = await db.execute(
  764. select(
  765. PrintLogEntry.duration_seconds,
  766. PrintLogEntry.started_at,
  767. PrintLogEntry.completed_at,
  768. ).where(*base_conditions)
  769. )
  770. total_seconds = 0
  771. for duration_seconds, started_at, completed_at in time_rows.all():
  772. if duration_seconds:
  773. total_seconds += duration_seconds
  774. elif started_at and completed_at:
  775. elapsed = (completed_at - started_at).total_seconds()
  776. if elapsed > 0:
  777. total_seconds += int(elapsed)
  778. total_time = total_seconds / 3600 # Convert to hours
  779. filament_result = await db.execute(
  780. select(func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0)).where(*base_conditions)
  781. )
  782. total_filament = filament_result.scalar() or 0
  783. cost_result = await db.execute(select(func.sum(PrintLogEntry.cost)).where(*base_conditions))
  784. total_cost = cost_result.scalar() or 0
  785. # By filament type (split comma-separated values for multi-material prints)
  786. filament_type_result = await db.execute(
  787. select(PrintLogEntry.filament_type).where(PrintLogEntry.filament_type.isnot(None), *base_conditions)
  788. )
  789. prints_by_filament: dict[str, int] = {}
  790. for (filament_types,) in filament_type_result.all():
  791. for ftype in filament_types.split(","):
  792. ftype = ftype.strip()
  793. if ftype:
  794. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  795. # By printer
  796. printer_result = await db.execute(
  797. select(PrintLogEntry.printer_id, func.count(PrintLogEntry.id))
  798. .where(*base_conditions)
  799. .group_by(PrintLogEntry.printer_id)
  800. )
  801. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  802. # Time accuracy — compare each completed run's actual duration to the
  803. # slicer's estimate on the linked archive. Runs without a linked archive
  804. # (NULL archive_id) or without an estimate are excluded.
  805. accuracy_rows = await db.execute(
  806. select(
  807. PrintLogEntry.duration_seconds,
  808. PrintLogEntry.started_at,
  809. PrintLogEntry.completed_at,
  810. PrintLogEntry.printer_id,
  811. PrintArchive.print_time_seconds,
  812. )
  813. .join(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  814. .where(
  815. PrintLogEntry.status == "completed",
  816. PrintArchive.print_time_seconds.isnot(None),
  817. *base_conditions,
  818. )
  819. )
  820. average_accuracy = None
  821. accuracy_by_printer: dict[str, float] = {}
  822. accuracies: list[float] = []
  823. printer_accuracies: dict[str, list[float]] = {}
  824. for duration_seconds, started_at, completed_at, run_printer_id, estimate_seconds in accuracy_rows.all():
  825. actual_seconds = duration_seconds
  826. if not actual_seconds and started_at and completed_at:
  827. elapsed = (completed_at - started_at).total_seconds()
  828. actual_seconds = int(elapsed) if elapsed > 0 else None
  829. if not actual_seconds or not estimate_seconds:
  830. continue
  831. accuracy = (estimate_seconds / actual_seconds) * 100
  832. accuracies.append(accuracy)
  833. printer_key = str(run_printer_id) if run_printer_id else "unknown"
  834. printer_accuracies.setdefault(printer_key, []).append(accuracy)
  835. if accuracies:
  836. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  837. for printer_key, accs in printer_accuracies.items():
  838. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  839. # Energy totals - check which mode to use
  840. from backend.app.api.routes.settings import get_setting
  841. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  842. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  843. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  844. total_energy_kwh: float = 0.0
  845. total_energy_cost: float = 0.0
  846. energy_data_warming_up = False
  847. if energy_tracking_mode == "total" and not date_from and not date_to:
  848. # All-time total consumption — read live lifetime counters.
  849. total_energy_kwh = await _sum_live_plug_totals(db)
  850. total_energy_cost = total_energy_kwh * energy_cost_per_kwh
  851. elif energy_tracking_mode == "total":
  852. # Total consumption mode with a date filter (#941): use hourly snapshots
  853. # to compute per-plug (endpoint - baseline) deltas.
  854. total_energy_kwh, energy_data_warming_up = await _sum_snapshot_deltas(
  855. db,
  856. dt_from=(datetime.combine(date_from, time.min, tzinfo=timezone.utc) if date_from else None),
  857. dt_to=(datetime.combine(date_to, time.max, tzinfo=timezone.utc) if date_to else None),
  858. )
  859. total_energy_cost = total_energy_kwh * energy_cost_per_kwh
  860. else:
  861. # Per-print mode: sum the per-run energy column from PrintLogEntry.
  862. energy_kwh_result = await db.execute(select(func.sum(PrintLogEntry.energy_kwh)).where(*base_conditions))
  863. total_energy_kwh = energy_kwh_result.scalar() or 0
  864. energy_cost_result = await db.execute(select(func.sum(PrintLogEntry.energy_cost)).where(*base_conditions))
  865. total_energy_cost = energy_cost_result.scalar() or 0
  866. return ArchiveStats(
  867. total_prints=total_prints,
  868. successful_prints=successful_prints,
  869. failed_prints=failed_prints,
  870. cancelled_prints=cancelled_prints,
  871. total_print_time_hours=round(total_time, 1),
  872. total_filament_grams=round(total_filament, 1),
  873. total_cost=round(total_cost, 2),
  874. prints_by_filament_type=prints_by_filament,
  875. prints_by_printer=prints_by_printer,
  876. average_time_accuracy=average_accuracy,
  877. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  878. total_energy_kwh=round(total_energy_kwh, 3),
  879. total_energy_cost=round(total_energy_cost, 3),
  880. energy_data_warming_up=energy_data_warming_up,
  881. )
  882. async def _sum_live_plug_totals(db: AsyncSession) -> float:
  883. """Sum the live lifetime counter from every smart plug.
  884. Used for all-time "total consumption" mode. Only the current value is
  885. available so this can't be date-filtered — use `_sum_snapshot_deltas` for
  886. that case.
  887. """
  888. from backend.app.api.routes.settings import get_setting
  889. from backend.app.models.smart_plug import SmartPlug
  890. from backend.app.services.homeassistant import homeassistant_service
  891. from backend.app.services.mqtt_relay import mqtt_relay
  892. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  893. from backend.app.services.tasmota import tasmota_service
  894. plugs_result = await db.execute(select(SmartPlug))
  895. plugs = list(plugs_result.scalars().all())
  896. ha_url = await get_setting(db, "ha_url") or ""
  897. ha_token = await get_setting(db, "ha_token") or ""
  898. homeassistant_service.configure(ha_url, ha_token)
  899. total = 0.0
  900. for plug in plugs:
  901. if plug.plug_type == "tasmota":
  902. energy = await tasmota_service.get_energy(plug)
  903. if energy and energy.get("total") is not None:
  904. total += energy["total"]
  905. elif plug.plug_type == "homeassistant":
  906. energy = await homeassistant_service.get_energy(plug)
  907. if energy and energy.get("total") is not None:
  908. total += energy["total"]
  909. elif plug.plug_type == "mqtt":
  910. # MQTT plugs only expose today's counter, not lifetime.
  911. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  912. if mqtt_data and mqtt_data.energy is not None:
  913. total += mqtt_data.energy
  914. elif plug.plug_type == "rest":
  915. energy = await rest_smart_plug_service.get_energy(plug)
  916. if energy and energy.get("today") is not None:
  917. total += energy["today"]
  918. return total
  919. async def _sum_snapshot_deltas(
  920. db: AsyncSession,
  921. *,
  922. dt_from: datetime | None,
  923. dt_to: datetime | None,
  924. ) -> tuple[float, bool]:
  925. """Sum per-plug energy consumption over a date range using hourly snapshots.
  926. For each plug:
  927. * baseline = last snapshot at or before `dt_from` (ideal)
  928. — if missing, fall back to the earliest snapshot ever
  929. recorded for the plug and flag the result as warming up.
  930. * endpoint = last snapshot at or before `dt_to` (or most recent overall)
  931. * delta = max(0, endpoint - baseline) — clamp counter resets to 0.
  932. Returns (total_kwh, warming_up). `warming_up = True` means at least one plug
  933. had no baseline before `dt_from` (fresh install or fresh upgrade), so the
  934. result undercounts the beginning of the range.
  935. """
  936. from backend.app.models.smart_plug import SmartPlug
  937. from backend.app.models.smart_plug_energy_snapshot import SmartPlugEnergySnapshot
  938. plug_ids_result = await db.execute(select(SmartPlug.id))
  939. plug_ids = [row[0] for row in plug_ids_result.all()]
  940. if not plug_ids:
  941. return 0.0, False
  942. total = 0.0
  943. warming_up = False
  944. for plug_id in plug_ids:
  945. baseline: float | None = None
  946. if dt_from is not None:
  947. baseline_q = await db.execute(
  948. select(SmartPlugEnergySnapshot.lifetime_kwh)
  949. .where(
  950. SmartPlugEnergySnapshot.plug_id == plug_id,
  951. SmartPlugEnergySnapshot.recorded_at <= dt_from,
  952. )
  953. .order_by(SmartPlugEnergySnapshot.recorded_at.desc())
  954. .limit(1)
  955. )
  956. baseline = baseline_q.scalar()
  957. if baseline is None:
  958. # No snapshot before range start — fall back to the earliest
  959. # snapshot ever recorded. Result undercounts the pre-first-snapshot
  960. # portion of the range; signal that to the frontend.
  961. earliest_q = await db.execute(
  962. select(SmartPlugEnergySnapshot.lifetime_kwh)
  963. .where(SmartPlugEnergySnapshot.plug_id == plug_id)
  964. .order_by(SmartPlugEnergySnapshot.recorded_at.asc())
  965. .limit(1)
  966. )
  967. baseline = earliest_q.scalar()
  968. if baseline is None:
  969. # No snapshots at all for this plug yet.
  970. warming_up = True
  971. continue
  972. warming_up = True
  973. endpoint_conditions = [SmartPlugEnergySnapshot.plug_id == plug_id]
  974. if dt_to is not None:
  975. endpoint_conditions.append(SmartPlugEnergySnapshot.recorded_at <= dt_to)
  976. endpoint_q = await db.execute(
  977. select(SmartPlugEnergySnapshot.lifetime_kwh)
  978. .where(*endpoint_conditions)
  979. .order_by(SmartPlugEnergySnapshot.recorded_at.desc())
  980. .limit(1)
  981. )
  982. endpoint = endpoint_q.scalar()
  983. if endpoint is None:
  984. continue
  985. total += max(0.0, endpoint - baseline)
  986. return total, warming_up
  987. @router.get("/tags")
  988. async def get_all_tags(
  989. db: AsyncSession = Depends(get_db),
  990. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  991. ):
  992. """List all unique tags with usage counts.
  993. Returns a list of tags sorted by count (descending), then by name.
  994. """
  995. # Query all archives with non-null tags
  996. result = await db.execute(
  997. select(PrintArchive.tags).where(PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None))
  998. )
  999. all_tags_rows = result.all()
  1000. # Count occurrences of each tag
  1001. tag_counts: dict[str, int] = {}
  1002. for (tags_str,) in all_tags_rows:
  1003. if tags_str:
  1004. for tag in tags_str.split(","):
  1005. tag = tag.strip()
  1006. if tag:
  1007. tag_counts[tag] = tag_counts.get(tag, 0) + 1
  1008. # Convert to list and sort by count (desc), then name (asc)
  1009. tags_list = [{"name": name, "count": count} for name, count in tag_counts.items()]
  1010. tags_list.sort(key=lambda x: (-x["count"], x["name"].lower()))
  1011. return tags_list
  1012. @router.put("/tags/{tag_name}")
  1013. async def rename_tag(
  1014. tag_name: str,
  1015. request: Request,
  1016. db: AsyncSession = Depends(get_db),
  1017. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1018. ):
  1019. """Rename a tag across all archives.
  1020. Request body should contain {"new_name": "new tag name"}.
  1021. Returns the count of affected archives.
  1022. """
  1023. body = await request.json()
  1024. new_name = body.get("new_name", "").strip()
  1025. if not new_name:
  1026. raise HTTPException(400, "new_name is required")
  1027. if new_name == tag_name:
  1028. return {"affected": 0}
  1029. # Find all archives containing the old tag
  1030. result = await db.execute(
  1031. select(PrintArchive).where(PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None))
  1032. )
  1033. archives = list(result.scalars().all())
  1034. affected = 0
  1035. for archive in archives:
  1036. if not archive.tags:
  1037. continue
  1038. tags = [t.strip() for t in archive.tags.split(",")]
  1039. if tag_name in tags:
  1040. # Replace old tag with new tag
  1041. new_tags = [new_name if t == tag_name else t for t in tags]
  1042. # Remove duplicates while preserving order
  1043. seen = set()
  1044. unique_tags = []
  1045. for t in new_tags:
  1046. if t not in seen:
  1047. seen.add(t)
  1048. unique_tags.append(t)
  1049. archive.tags = ", ".join(unique_tags)
  1050. affected += 1
  1051. await db.commit()
  1052. return {"affected": affected}
  1053. @router.delete("/tags/{tag_name}")
  1054. async def delete_tag(
  1055. tag_name: str,
  1056. db: AsyncSession = Depends(get_db),
  1057. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1058. ):
  1059. """Delete a tag from all archives.
  1060. Returns the count of affected archives.
  1061. """
  1062. # Find all archives containing the tag
  1063. result = await db.execute(
  1064. select(PrintArchive).where(PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None))
  1065. )
  1066. archives = list(result.scalars().all())
  1067. affected = 0
  1068. for archive in archives:
  1069. if not archive.tags:
  1070. continue
  1071. tags = [t.strip() for t in archive.tags.split(",")]
  1072. if tag_name in tags:
  1073. # Remove the tag
  1074. new_tags = [t for t in tags if t != tag_name]
  1075. archive.tags = ", ".join(new_tags) if new_tags else None
  1076. affected += 1
  1077. await db.commit()
  1078. return {"affected": affected}
  1079. @router.get("/{archive_id}", response_model=ArchiveResponse)
  1080. async def get_archive(
  1081. archive_id: int,
  1082. db: AsyncSession = Depends(get_db),
  1083. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1084. ):
  1085. """Get a specific archive."""
  1086. service = ArchiveService(db)
  1087. archive = await service.get_archive(archive_id)
  1088. # Soft-deleted archives are hidden from the UI (#1343) — surface them as
  1089. # 404 here too so a stale bookmark / direct URL doesn't expose a row the
  1090. # user has already removed. The hard-delete (?purge_stats=true) path
  1091. # bypasses this check by querying PrintArchive directly.
  1092. if not archive or archive.deleted_at is not None:
  1093. raise HTTPException(404, "Archive not found")
  1094. # Find duplicates
  1095. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  1096. duplicates = await service.find_duplicates(
  1097. archive_id=archive.id,
  1098. content_hash=archive.content_hash,
  1099. print_name=archive.print_name,
  1100. makerworld_model_id=makerworld_id,
  1101. )
  1102. run_aggregates = await _load_run_aggregates(db, [archive.id])
  1103. return archive_to_response(archive, duplicates, run_aggregate=run_aggregates.get(archive.id))
  1104. @router.get("/{archive_id}/runs", response_model=PrintLogResponse)
  1105. async def list_archive_runs(
  1106. archive_id: int,
  1107. db: AsyncSession = Depends(get_db),
  1108. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1109. ):
  1110. """List PrintLogEntry rows for this archive — one per print event.
  1111. Newest first. Drives the per-archive "Print Log" view (#1378).
  1112. """
  1113. from backend.app.models.print_log import PrintLogEntry
  1114. from backend.app.schemas.print_log import PrintLogEntrySchema
  1115. archive = await db.get(PrintArchive, archive_id)
  1116. if not archive or archive.deleted_at is not None:
  1117. raise HTTPException(404, "Archive not found")
  1118. rows = await db.execute(
  1119. select(PrintLogEntry)
  1120. .where(PrintLogEntry.archive_id == archive_id)
  1121. .order_by(PrintLogEntry.started_at.desc().nulls_last(), PrintLogEntry.id.desc())
  1122. )
  1123. entries = list(rows.scalars().all())
  1124. items = [PrintLogEntrySchema.model_validate(e, from_attributes=True) for e in entries]
  1125. return PrintLogResponse(items=items, total=len(items))
  1126. @router.get("/{archive_id}/similar")
  1127. async def find_similar_archives(
  1128. archive_id: int,
  1129. limit: int = 10,
  1130. db: AsyncSession = Depends(get_db),
  1131. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1132. ):
  1133. """Find archives with similar settings for comparison.
  1134. Returns archives that match by:
  1135. - Same print name (highest priority)
  1136. - Same file content hash
  1137. - Same filament type
  1138. """
  1139. from backend.app.services.archive_comparison import ArchiveComparisonService
  1140. service = ArchiveComparisonService(db)
  1141. try:
  1142. return await service.find_similar_archives(archive_id, limit=limit)
  1143. except ValueError as e:
  1144. raise HTTPException(404, str(e))
  1145. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  1146. async def update_archive(
  1147. archive_id: int,
  1148. update_data: ArchiveUpdate,
  1149. db: AsyncSession = Depends(get_db),
  1150. auth_result: tuple[User | None, bool] = Depends(
  1151. require_ownership_permission(
  1152. Permission.ARCHIVES_UPDATE_ALL,
  1153. Permission.ARCHIVES_UPDATE_OWN,
  1154. )
  1155. ),
  1156. ):
  1157. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  1158. from sqlalchemy.orm import selectinload
  1159. user, can_modify_all = auth_result
  1160. result = await db.execute(
  1161. select(PrintArchive)
  1162. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1163. .where(PrintArchive.id == archive_id)
  1164. )
  1165. archive = result.scalar_one_or_none()
  1166. if not archive:
  1167. raise HTTPException(404, "Archive not found")
  1168. # Ownership check
  1169. if not can_modify_all:
  1170. if archive.created_by_id != user.id:
  1171. raise HTTPException(403, "You can only update your own archives")
  1172. update_payload = update_data.model_dump(exclude_unset=True)
  1173. for field, value in update_payload.items():
  1174. setattr(archive, field, value)
  1175. # #1444: Mirror per-run classification fields to the most recent
  1176. # PrintLogEntry for this archive. PrintLogEntry.failure_reason is captured
  1177. # once at print-completion time from archive.failure_reason — which is
  1178. # NULL until the user classifies the failure via the Edit Archive modal.
  1179. # Without this mirror the Failure Analysis widget (which groups by
  1180. # print_log_entries.failure_reason) keeps showing "Unknown" forever.
  1181. # Same desync hits status: flipping it in the modal wouldn't update the
  1182. # entry either. Only the latest entry is touched because that's the run
  1183. # the modal is implicitly showing (archive.failure_reason / status are
  1184. # overwritten on each reprint to reflect the latest run's outcome).
  1185. mirror_fields = {"failure_reason", "status"}
  1186. to_mirror = {k: v for k, v in update_payload.items() if k in mirror_fields}
  1187. if to_mirror:
  1188. from backend.app.models.print_log import PrintLogEntry
  1189. latest_entry = await db.scalar(
  1190. select(PrintLogEntry)
  1191. .where(PrintLogEntry.archive_id == archive_id)
  1192. .order_by(PrintLogEntry.id.desc())
  1193. .limit(1)
  1194. )
  1195. if latest_entry is not None:
  1196. for field, value in to_mirror.items():
  1197. setattr(latest_entry, field, value)
  1198. await db.commit()
  1199. # Re-fetch with relationships loaded after commit
  1200. result = await db.execute(
  1201. select(PrintArchive)
  1202. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1203. .where(PrintArchive.id == archive_id)
  1204. )
  1205. archive = result.scalar_one_or_none()
  1206. return archive_to_response(archive)
  1207. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  1208. async def toggle_favorite(
  1209. archive_id: int,
  1210. db: AsyncSession = Depends(get_db),
  1211. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  1212. ):
  1213. """Toggle favorite status for an archive."""
  1214. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1215. archive = result.scalar_one_or_none()
  1216. if not archive:
  1217. raise HTTPException(404, "Archive not found")
  1218. archive.is_favorite = not archive.is_favorite
  1219. await db.commit()
  1220. await db.refresh(archive)
  1221. return archive
  1222. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  1223. async def rescan_archive(
  1224. archive_id: int,
  1225. db: AsyncSession = Depends(get_db),
  1226. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1227. ):
  1228. """Rescan the 3MF file and update metadata."""
  1229. from backend.app.api.routes.settings import get_setting
  1230. from backend.app.services.archive import ThreeMFParser
  1231. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1232. archive = result.scalar_one_or_none()
  1233. if not archive:
  1234. raise HTTPException(404, "Archive not found")
  1235. file_path = settings.base_dir / archive.file_path
  1236. if not file_path.is_file():
  1237. raise HTTPException(404, "Archive file not found")
  1238. # Parse the 3MF file
  1239. parser = ThreeMFParser(file_path)
  1240. metadata = parser.parse()
  1241. # Update fields from metadata
  1242. if metadata.get("filament_type"):
  1243. archive.filament_type = metadata["filament_type"]
  1244. if metadata.get("filament_color"):
  1245. archive.filament_color = metadata["filament_color"]
  1246. if metadata.get("print_time_seconds"):
  1247. archive.print_time_seconds = metadata["print_time_seconds"]
  1248. if metadata.get("filament_used_grams"):
  1249. archive.filament_used_grams = metadata["filament_used_grams"]
  1250. if metadata.get("layer_height"):
  1251. archive.layer_height = metadata["layer_height"]
  1252. if metadata.get("nozzle_diameter"):
  1253. archive.nozzle_diameter = metadata["nozzle_diameter"]
  1254. if metadata.get("bed_temperature"):
  1255. archive.bed_temperature = metadata["bed_temperature"]
  1256. if metadata.get("bed_type"):
  1257. archive.bed_type = metadata["bed_type"]
  1258. if metadata.get("nozzle_temperature"):
  1259. archive.nozzle_temperature = metadata["nozzle_temperature"]
  1260. if metadata.get("makerworld_url"):
  1261. archive.makerworld_url = metadata["makerworld_url"]
  1262. if metadata.get("designer"):
  1263. archive.designer = metadata["designer"]
  1264. # Calculate cost: prefer spool-based cost if available, else catalog-based.
  1265. # When spool-based costs exist but don't cover every filament gram used
  1266. # (#1344), fall back to the global default rate for the untracked weight
  1267. # so the displayed cost still reflects the whole print.
  1268. if archive.filament_used_grams and archive.filament_type:
  1269. default_cost_setting = await get_setting(db, "default_filament_cost")
  1270. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1271. usage_result = await db.execute(
  1272. select(
  1273. func.sum(SpoolUsageHistory.cost),
  1274. func.sum(SpoolUsageHistory.weight_used),
  1275. ).where(SpoolUsageHistory.archive_id == archive.id)
  1276. )
  1277. usage_cost_row = usage_result.one()
  1278. usage_cost = usage_cost_row[0]
  1279. tracked_grams = float(usage_cost_row[1] or 0)
  1280. if usage_cost is not None and usage_cost > 0:
  1281. total_cost = float(usage_cost)
  1282. untracked_grams = max(0.0, archive.filament_used_grams - tracked_grams)
  1283. if untracked_grams > 0 and default_cost_per_kg > 0:
  1284. total_cost += (untracked_grams / 1000.0) * default_cost_per_kg
  1285. archive.cost = float(Decimal(str(total_cost)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
  1286. else:
  1287. primary_type = archive.filament_type.split(",")[0].strip()
  1288. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  1289. filament = filament_result.scalar_one_or_none()
  1290. if filament:
  1291. archive.cost = float(
  1292. Decimal(str((archive.filament_used_grams / 1000) * filament.cost_per_kg)).quantize(
  1293. Decimal("0.01"), rounding=ROUND_HALF_UP
  1294. )
  1295. )
  1296. else:
  1297. archive.cost = float(
  1298. Decimal(str((archive.filament_used_grams / 1000) * default_cost_per_kg)).quantize(
  1299. Decimal("0.01"), rounding=ROUND_HALF_UP
  1300. )
  1301. )
  1302. await db.commit()
  1303. await db.refresh(archive)
  1304. return archive
  1305. @router.post("/recalculate-costs")
  1306. async def recalculate_all_costs(
  1307. db: AsyncSession = Depends(get_db),
  1308. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1309. ):
  1310. """Recalculate costs for all archives based on filament usage and prices."""
  1311. from backend.app.api.routes.settings import get_setting
  1312. result = await db.execute(select(PrintArchive))
  1313. archives = list(result.scalars().all())
  1314. # Load all filaments for lookup
  1315. filament_result = await db.execute(select(Filament))
  1316. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  1317. # Get default filament cost from settings
  1318. default_cost_setting = await get_setting(db, "default_filament_cost")
  1319. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1320. # Pre-fetch all usage costs and tracked weight by archive_id.
  1321. # Tracked weight is used to top-up the cost at the default rate for any
  1322. # filament grams not covered by an inventory spool (#1344).
  1323. usage_costs_result = await db.execute(
  1324. select(
  1325. SpoolUsageHistory.archive_id,
  1326. func.sum(SpoolUsageHistory.cost),
  1327. func.sum(SpoolUsageHistory.weight_used),
  1328. ).group_by(SpoolUsageHistory.archive_id)
  1329. )
  1330. usage_costs = usage_costs_result.fetchall()
  1331. cost_map = {
  1332. row[0]: (row[1], float(row[2] or 0))
  1333. for row in usage_costs
  1334. if row[0] is not None and row[1] is not None and row[1] > 0
  1335. }
  1336. updated = 0
  1337. for archive in archives:
  1338. usage = cost_map.get(archive.id)
  1339. if usage is not None:
  1340. usage_cost, tracked_grams = usage
  1341. total_cost = float(usage_cost)
  1342. archive_grams = float(archive.filament_used_grams or 0)
  1343. untracked_grams = max(0.0, archive_grams - tracked_grams)
  1344. if untracked_grams > 0 and default_cost_per_kg > 0:
  1345. total_cost += (untracked_grams / 1000.0) * default_cost_per_kg
  1346. new_cost = round(total_cost, 2)
  1347. else:
  1348. # Fallback: sum costs for old records by print_name
  1349. usage_result = await db.execute(
  1350. select(func.sum(SpoolUsageHistory.cost)).where(
  1351. SpoolUsageHistory.print_name == archive.print_name,
  1352. SpoolUsageHistory.archive_id.is_(None),
  1353. )
  1354. )
  1355. fallback_cost = usage_result.scalar()
  1356. if fallback_cost is not None and fallback_cost > 0:
  1357. new_cost = round(fallback_cost, 2)
  1358. elif archive.filament_used_grams and archive.filament_type:
  1359. primary_type = archive.filament_type.split(",")[0].strip()
  1360. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  1361. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  1362. else:
  1363. new_cost = None
  1364. if new_cost is not None and archive.cost != new_cost:
  1365. archive.cost = new_cost
  1366. updated += 1
  1367. await db.commit()
  1368. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  1369. @router.post("/rescan-all")
  1370. async def rescan_all_archives(
  1371. db: AsyncSession = Depends(get_db),
  1372. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1373. ):
  1374. """Rescan all archives and update their metadata."""
  1375. from backend.app.services.archive import ThreeMFParser
  1376. result = await db.execute(select(PrintArchive))
  1377. archives = list(result.scalars().all())
  1378. updated = 0
  1379. errors = []
  1380. for archive in archives:
  1381. try:
  1382. file_path = settings.base_dir / archive.file_path
  1383. if not file_path.is_file():
  1384. errors.append({"id": archive.id, "error": "File not found"})
  1385. continue
  1386. parser = ThreeMFParser(file_path)
  1387. metadata = parser.parse()
  1388. if metadata.get("filament_type"):
  1389. archive.filament_type = metadata["filament_type"]
  1390. if metadata.get("filament_color"):
  1391. archive.filament_color = metadata["filament_color"]
  1392. if metadata.get("print_time_seconds"):
  1393. archive.print_time_seconds = metadata["print_time_seconds"]
  1394. if metadata.get("filament_used_grams"):
  1395. archive.filament_used_grams = metadata["filament_used_grams"]
  1396. if metadata.get("layer_height"):
  1397. archive.layer_height = metadata["layer_height"]
  1398. if metadata.get("nozzle_diameter"):
  1399. archive.nozzle_diameter = metadata["nozzle_diameter"]
  1400. if metadata.get("makerworld_url"):
  1401. archive.makerworld_url = metadata["makerworld_url"]
  1402. if metadata.get("designer"):
  1403. archive.designer = metadata["designer"]
  1404. updated += 1
  1405. except Exception as e:
  1406. logger.exception("Failed to rescan archive %s: %s", archive.id, e)
  1407. errors.append({"id": archive.id, "error": "Failed to parse 3MF file"})
  1408. await db.commit()
  1409. return {"updated": updated, "errors": errors}
  1410. @router.get("/{archive_id}/duplicates")
  1411. async def get_archive_duplicates(
  1412. archive_id: int,
  1413. db: AsyncSession = Depends(get_db),
  1414. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1415. ):
  1416. """Get duplicates for a specific archive."""
  1417. service = ArchiveService(db)
  1418. archive = await service.get_archive(archive_id)
  1419. if not archive:
  1420. raise HTTPException(404, "Archive not found")
  1421. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  1422. duplicates = await service.find_duplicates(
  1423. archive_id=archive.id,
  1424. content_hash=archive.content_hash,
  1425. print_name=archive.print_name,
  1426. makerworld_model_id=makerworld_id,
  1427. )
  1428. return {"duplicates": duplicates, "count": len(duplicates)}
  1429. @router.post("/backfill-hashes")
  1430. async def backfill_content_hashes(
  1431. db: AsyncSession = Depends(get_db),
  1432. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1433. ):
  1434. """Compute and store content hashes for all archives missing them."""
  1435. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  1436. archives = list(result.scalars().all())
  1437. updated = 0
  1438. errors = []
  1439. for archive in archives:
  1440. try:
  1441. file_path = settings.base_dir / archive.file_path
  1442. if not file_path.is_file():
  1443. errors.append({"id": archive.id, "error": "File not found"})
  1444. continue
  1445. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  1446. updated += 1
  1447. except Exception as e:
  1448. logger.exception("Failed to compute hash for archive %s: %s", archive.id, e)
  1449. errors.append({"id": archive.id, "error": "Failed to compute hash"})
  1450. await db.commit()
  1451. return {"updated": updated, "errors": errors}
  1452. @router.delete("/{archive_id}")
  1453. async def delete_archive(
  1454. archive_id: int,
  1455. purge_stats: bool = Query(
  1456. False,
  1457. description=(
  1458. "When false (default) the archive is soft-deleted — files removed "
  1459. "from disk, row hidden from listings, but its filament / energy / "
  1460. "time / cost contribution stays in Quick Stats. Set true to also "
  1461. "drop the row from statistics (#1343)."
  1462. ),
  1463. ),
  1464. db: AsyncSession = Depends(get_db),
  1465. auth_result: tuple[User | None, bool] = Depends(
  1466. require_ownership_permission(
  1467. Permission.ARCHIVES_DELETE_ALL,
  1468. Permission.ARCHIVES_DELETE_OWN,
  1469. )
  1470. ),
  1471. ):
  1472. """Delete an archive (soft by default; ``?purge_stats=true`` to hard-delete)."""
  1473. user, can_modify_all = auth_result
  1474. # Get archive first to check ownership
  1475. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1476. archive = result.scalar_one_or_none()
  1477. if not archive:
  1478. raise HTTPException(404, "Archive not found")
  1479. # Ownership check
  1480. if not can_modify_all:
  1481. if archive.created_by_id != user.id:
  1482. raise HTTPException(403, "You can only delete your own archives")
  1483. service = ArchiveService(db)
  1484. if purge_stats:
  1485. # Hard-delete the linked PrintLogEntry rows first so their filament /
  1486. # cost / count contributions disappear from /archives/stats. The FK is
  1487. # ON DELETE SET NULL, so without this delete the runs would survive
  1488. # the archive row and keep showing up in totals (#1343 / #1378).
  1489. from sqlalchemy import delete as sa_delete
  1490. from backend.app.models.print_log import PrintLogEntry
  1491. await db.execute(sa_delete(PrintLogEntry).where(PrintLogEntry.archive_id == archive_id))
  1492. await db.commit()
  1493. if not await service.delete_archive(archive_id):
  1494. raise HTTPException(404, "Archive not found")
  1495. return {"status": "deleted", "purged_from_stats": True}
  1496. if not await service.soft_delete_archive(archive_id):
  1497. raise HTTPException(404, "Archive not found")
  1498. return {"status": "deleted", "purged_from_stats": False}
  1499. @router.get("/{archive_id}/download")
  1500. async def download_archive(
  1501. archive_id: int,
  1502. inline: bool = False,
  1503. db: AsyncSession = Depends(get_db),
  1504. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1505. ):
  1506. """Download the 3MF file."""
  1507. service = ArchiveService(db)
  1508. archive = await service.get_archive(archive_id)
  1509. if not archive:
  1510. raise HTTPException(404, "Archive not found")
  1511. file_path = settings.base_dir / archive.file_path
  1512. if not file_path.is_file():
  1513. raise HTTPException(404, "File not found")
  1514. # Use inline disposition to let browser/OS handle file association
  1515. content_disposition = "inline" if inline else "attachment"
  1516. return FileResponse(
  1517. path=file_path,
  1518. filename=archive.filename,
  1519. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1520. content_disposition_type=content_disposition,
  1521. )
  1522. @router.get("/{archive_id}/file/{filename}")
  1523. async def download_archive_with_filename(
  1524. archive_id: int,
  1525. filename: str,
  1526. db: AsyncSession = Depends(get_db),
  1527. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1528. ):
  1529. """Download the 3MF file with filename in URL."""
  1530. service = ArchiveService(db)
  1531. archive = await service.get_archive(archive_id)
  1532. if not archive:
  1533. raise HTTPException(404, "Archive not found")
  1534. file_path = settings.base_dir / archive.file_path
  1535. if not file_path.is_file():
  1536. raise HTTPException(404, "File not found")
  1537. return FileResponse(
  1538. path=file_path,
  1539. filename=archive.filename,
  1540. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1541. )
  1542. @router.post("/{archive_id}/slicer-token")
  1543. async def create_archive_slicer_token(
  1544. archive_id: int,
  1545. db: AsyncSession = Depends(get_db),
  1546. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1547. ):
  1548. """Create a short-lived download token for opening files in slicer applications.
  1549. Slicer protocol handlers (bambustudioopen://, orcaslicer://) cannot send
  1550. auth headers, so they use this token in the URL path instead.
  1551. """
  1552. from backend.app.core.auth import create_slicer_download_token
  1553. service = ArchiveService(db)
  1554. archive = await service.get_archive(archive_id)
  1555. if not archive:
  1556. raise HTTPException(404, "Archive not found")
  1557. token = await create_slicer_download_token("archive", archive_id)
  1558. return {"token": token}
  1559. @router.get("/{archive_id}/dl/{token}/{filename}")
  1560. async def download_archive_for_slicer(
  1561. archive_id: int,
  1562. token: str,
  1563. filename: str,
  1564. db: AsyncSession = Depends(get_db),
  1565. ):
  1566. """Download 3MF file using a slicer download token.
  1567. Token-authenticated (no auth headers needed). The token is short-lived
  1568. and single-use, created by POST /{archive_id}/slicer-token.
  1569. Filename is at the end of the URL so slicers can detect the file format.
  1570. """
  1571. from backend.app.core.auth import verify_slicer_download_token
  1572. if not await verify_slicer_download_token(token, "archive", archive_id):
  1573. raise HTTPException(403, "Invalid or expired download token")
  1574. service = ArchiveService(db)
  1575. archive = await service.get_archive(archive_id)
  1576. if not archive:
  1577. raise HTTPException(404, "Archive not found")
  1578. file_path = settings.base_dir / archive.file_path
  1579. if not file_path.is_file():
  1580. raise HTTPException(404, "File not found")
  1581. return FileResponse(
  1582. path=file_path,
  1583. filename=archive.filename,
  1584. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1585. )
  1586. @router.get("/{archive_id}/thumbnail")
  1587. async def get_thumbnail(
  1588. archive_id: int,
  1589. db: AsyncSession = Depends(get_db),
  1590. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1591. ):
  1592. """Get the thumbnail image.
  1593. Requires a stream token query param (?token=xxx) when auth is enabled.
  1594. """
  1595. service = ArchiveService(db)
  1596. archive = await service.get_archive(archive_id)
  1597. if not archive or not archive.thumbnail_path:
  1598. raise HTTPException(404, "Thumbnail not found")
  1599. thumb_path = settings.base_dir / archive.thumbnail_path
  1600. if not thumb_path.exists():
  1601. raise HTTPException(404, "Thumbnail file not found")
  1602. # Use file modification time as ETag to bust cache
  1603. mtime = int(thumb_path.stat().st_mtime)
  1604. return FileResponse(
  1605. path=thumb_path,
  1606. media_type="image/png",
  1607. headers={
  1608. "Cache-Control": "no-cache, must-revalidate",
  1609. "ETag": f'"{mtime}"',
  1610. },
  1611. )
  1612. @router.get("/{archive_id}/timelapse")
  1613. async def get_timelapse(
  1614. archive_id: int,
  1615. db: AsyncSession = Depends(get_db),
  1616. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1617. ):
  1618. """Get the timelapse video.
  1619. Requires a stream token query param (?token=xxx) when auth is enabled.
  1620. """
  1621. service = ArchiveService(db)
  1622. archive = await service.get_archive(archive_id)
  1623. if not archive or not archive.timelapse_path:
  1624. raise HTTPException(404, "Timelapse not found")
  1625. timelapse_path = settings.base_dir / archive.timelapse_path
  1626. if not timelapse_path.exists():
  1627. raise HTTPException(404, "Timelapse file not found")
  1628. # Use file modification time as ETag to bust cache after processing
  1629. mtime = int(timelapse_path.stat().st_mtime)
  1630. # Detect media type from file extension (AVI from P1S before background conversion)
  1631. suffix = timelapse_path.suffix.lower()
  1632. media_type = {".mp4": "video/mp4", ".avi": "video/x-msvideo", ".mkv": "video/x-matroska"}.get(suffix, "video/mp4")
  1633. ext = suffix if suffix in (".mp4", ".avi", ".mkv") else ".mp4"
  1634. return FileResponse(
  1635. path=timelapse_path,
  1636. media_type=media_type,
  1637. filename=f"{archive.print_name or 'timelapse'}{ext}",
  1638. headers={
  1639. "Cache-Control": "no-cache, must-revalidate",
  1640. "ETag": f'"{mtime}"',
  1641. },
  1642. )
  1643. @router.delete("/{archive_id}/timelapse")
  1644. async def delete_timelapse(
  1645. archive_id: int,
  1646. db: AsyncSession = Depends(get_db),
  1647. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  1648. ):
  1649. """Remove the timelapse video from an archive."""
  1650. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1651. archive = result.scalar_one_or_none()
  1652. if not archive:
  1653. raise HTTPException(404, "Archive not found")
  1654. if not archive.timelapse_path:
  1655. raise HTTPException(404, "No timelapse attached to this archive")
  1656. # Delete the file
  1657. timelapse_path = settings.base_dir / archive.timelapse_path
  1658. if timelapse_path.exists():
  1659. timelapse_path.unlink()
  1660. # Clear the path in database
  1661. archive.timelapse_path = None
  1662. await db.commit()
  1663. return {"status": "deleted"}
  1664. @router.post("/{archive_id}/timelapse/scan")
  1665. async def scan_timelapse(
  1666. archive_id: int,
  1667. db: AsyncSession = Depends(get_db),
  1668. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1669. ):
  1670. """Scan printer for timelapse matching this archive and attach it."""
  1671. from backend.app.models.printer import Printer
  1672. from backend.app.services.bambu_ftp import (
  1673. download_file_bytes_async,
  1674. get_ftp_retry_settings,
  1675. list_files_async,
  1676. with_ftp_retry,
  1677. )
  1678. service = ArchiveService(db)
  1679. archive = await service.get_archive(archive_id)
  1680. if not archive:
  1681. raise HTTPException(404, "Archive not found")
  1682. if archive.timelapse_path:
  1683. return {"status": "exists", "message": "Timelapse already attached"}
  1684. if not archive.printer_id:
  1685. raise HTTPException(400, "Archive has no associated printer")
  1686. # Get printer
  1687. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1688. printer = result.scalar_one_or_none()
  1689. if not printer:
  1690. raise HTTPException(404, "Printer not found")
  1691. # Get base name from archive filename (without .3mf extension)
  1692. base_name = Path(archive.filename).stem
  1693. # Scan timelapse directory on printer
  1694. # Different printer models use different paths
  1695. files = []
  1696. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1697. try:
  1698. files = await list_files_async(
  1699. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  1700. )
  1701. if files:
  1702. break
  1703. except Exception:
  1704. continue
  1705. if not files:
  1706. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  1707. # Look for matching timelapse
  1708. matching_file = None
  1709. video_files = [
  1710. f for f in files if not f.get("is_directory") and f.get("name", "").lower().endswith((".mp4", ".avi"))
  1711. ]
  1712. # Strategy 1: Match by print name in filename
  1713. for f in video_files:
  1714. fname = f.get("name", "")
  1715. if base_name.lower() in fname.lower():
  1716. matching_file = f
  1717. break
  1718. # Strategy 2: Match by timestamp proximity against print START time.
  1719. # Bambu timelapse filename embeds the print start time in printer-local clock.
  1720. # See _match_timelapse_by_timestamp for the offset-search rationale and why we
  1721. # intentionally don't try to match filename against end time here.
  1722. if not matching_file and archive.started_at:
  1723. candidate, diff = _match_timelapse_by_timestamp(video_files, archive.started_at)
  1724. if candidate is not None:
  1725. matching_file = candidate
  1726. logger.info("Matched timelapse by timestamp: %s (diff: %s)", candidate.get("name"), diff)
  1727. # Strategy 3: Use file modification time from FTP listing
  1728. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  1729. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  1730. from datetime import datetime, timedelta
  1731. _archive_start = archive.started_at
  1732. archive_end = archive.completed_at or archive.created_at
  1733. best_match = None
  1734. best_diff = timedelta(hours=24)
  1735. for f in video_files:
  1736. mtime = f.get("mtime")
  1737. if mtime:
  1738. # Timelapse file should be modified during or shortly after the print
  1739. # The mtime should be close to completion time (video finishes when print ends)
  1740. if archive_end:
  1741. diff = abs(mtime - archive_end)
  1742. if diff < best_diff:
  1743. best_diff = diff
  1744. best_match = f
  1745. logger.debug(
  1746. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  1747. )
  1748. if best_match and best_diff < timedelta(hours=2):
  1749. matching_file = best_match
  1750. logger.info("Matched timelapse by file mtime: %s (diff: %s)", best_match.get("name"), best_diff)
  1751. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  1752. # This handles cases where printer clock is wrong or timezone issues exist
  1753. if not matching_file and len(video_files) == 1:
  1754. from datetime import datetime, timedelta, timezone
  1755. archive_completed = archive.completed_at or archive.created_at
  1756. if archive_completed:
  1757. if archive_completed.tzinfo is None:
  1758. archive_completed = archive_completed.replace(tzinfo=timezone.utc)
  1759. time_since_completion = datetime.now(timezone.utc) - archive_completed
  1760. # If archive was completed within the last hour, assume the single timelapse is for it
  1761. if time_since_completion < timedelta(hours=1):
  1762. matching_file = video_files[0]
  1763. logger.info("Using single timelapse file as fallback: %s", video_files[0].get("name"))
  1764. # Note: We intentionally don't use a "most recent file" fallback because
  1765. # we can't verify if timelapse was actually enabled for this print.
  1766. # Instead, return the list of available files for manual selection.
  1767. if not matching_file:
  1768. # Return available files for manual selection
  1769. available_files = [
  1770. {
  1771. "name": f.get("name"),
  1772. "path": f.get("path"),
  1773. "size": f.get("size"),
  1774. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  1775. }
  1776. for f in video_files
  1777. ]
  1778. # Sort by mtime descending (most recent first)
  1779. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  1780. return {
  1781. "status": "not_found",
  1782. "message": "No matching timelapse found - please select manually",
  1783. "available_files": available_files,
  1784. }
  1785. # Download the timelapse - use the full path from the file listing
  1786. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  1787. # Get FTP retry settings
  1788. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1789. if ftp_retry_enabled:
  1790. timelapse_data = await with_ftp_retry(
  1791. download_file_bytes_async,
  1792. printer.ip_address,
  1793. printer.access_code,
  1794. remote_path,
  1795. socket_timeout=ftp_timeout,
  1796. printer_model=printer.model,
  1797. max_retries=ftp_retry_count,
  1798. retry_delay=ftp_retry_delay,
  1799. operation_name=f"Download timelapse {matching_file['name']}",
  1800. )
  1801. else:
  1802. timelapse_data = await download_file_bytes_async(
  1803. printer.ip_address,
  1804. printer.access_code,
  1805. remote_path,
  1806. socket_timeout=ftp_timeout,
  1807. printer_model=printer.model,
  1808. )
  1809. if not timelapse_data:
  1810. raise HTTPException(500, "Failed to download timelapse")
  1811. # Attach timelapse to archive
  1812. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  1813. if not success:
  1814. raise HTTPException(500, "Failed to attach timelapse")
  1815. return {
  1816. "status": "attached",
  1817. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  1818. "filename": matching_file["name"],
  1819. }
  1820. @router.post("/{archive_id}/timelapse/select")
  1821. async def select_timelapse(
  1822. archive_id: int,
  1823. filename: str = Query(..., description="Timelapse filename to attach"),
  1824. db: AsyncSession = Depends(get_db),
  1825. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1826. ):
  1827. """Manually select a timelapse from the printer to attach."""
  1828. from backend.app.models.printer import Printer
  1829. from backend.app.services.bambu_ftp import (
  1830. download_file_bytes_async,
  1831. get_ftp_retry_settings,
  1832. list_files_async,
  1833. with_ftp_retry,
  1834. )
  1835. service = ArchiveService(db)
  1836. archive = await service.get_archive(archive_id)
  1837. if not archive:
  1838. raise HTTPException(404, "Archive not found")
  1839. if not archive.printer_id:
  1840. raise HTTPException(400, "Archive has no associated printer")
  1841. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1842. printer = result.scalar_one_or_none()
  1843. if not printer:
  1844. raise HTTPException(404, "Printer not found")
  1845. # Find the file on the printer
  1846. files = []
  1847. remote_path = None
  1848. for timelapse_dir in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1849. try:
  1850. files = await list_files_async(
  1851. printer.ip_address, printer.access_code, timelapse_dir, printer_model=printer.model
  1852. )
  1853. for f in files:
  1854. if f.get("name") == filename:
  1855. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  1856. break
  1857. if remote_path:
  1858. break
  1859. except Exception:
  1860. continue
  1861. if not remote_path:
  1862. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  1863. # Download and attach
  1864. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1865. if ftp_retry_enabled:
  1866. timelapse_data = await with_ftp_retry(
  1867. download_file_bytes_async,
  1868. printer.ip_address,
  1869. printer.access_code,
  1870. remote_path,
  1871. socket_timeout=ftp_timeout,
  1872. printer_model=printer.model,
  1873. max_retries=ftp_retry_count,
  1874. retry_delay=ftp_retry_delay,
  1875. operation_name=f"Download timelapse {filename}",
  1876. )
  1877. else:
  1878. timelapse_data = await download_file_bytes_async(
  1879. printer.ip_address,
  1880. printer.access_code,
  1881. remote_path,
  1882. socket_timeout=ftp_timeout,
  1883. printer_model=printer.model,
  1884. )
  1885. if not timelapse_data:
  1886. raise HTTPException(500, "Failed to download timelapse")
  1887. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  1888. if not success:
  1889. raise HTTPException(500, "Failed to attach timelapse")
  1890. return {
  1891. "status": "attached",
  1892. "message": f"Timelapse '{filename}' attached successfully",
  1893. "filename": filename,
  1894. }
  1895. @router.post("/{archive_id}/timelapse/upload")
  1896. async def upload_timelapse(
  1897. archive_id: int,
  1898. file: UploadFile = File(...),
  1899. db: AsyncSession = Depends(get_db),
  1900. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1901. ):
  1902. """Manually upload a timelapse video to an archive."""
  1903. service = ArchiveService(db)
  1904. archive = await service.get_archive(archive_id)
  1905. if not archive:
  1906. raise HTTPException(404, "Archive not found")
  1907. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  1908. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  1909. content = await file.read()
  1910. safe_filename = _safe_filename(file.filename)
  1911. success = await service.attach_timelapse(archive_id, content, safe_filename)
  1912. if not success:
  1913. raise HTTPException(500, "Failed to attach timelapse")
  1914. return {"status": "attached", "filename": safe_filename}
  1915. @router.get("/{archive_id}/timelapse/info")
  1916. async def get_timelapse_info(
  1917. archive_id: int,
  1918. db: AsyncSession = Depends(get_db),
  1919. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1920. ):
  1921. """Get timelapse video metadata for editor."""
  1922. from backend.app.schemas.timelapse import TimelapseInfoResponse
  1923. from backend.app.services.timelapse_processor import TimelapseProcessor
  1924. service = ArchiveService(db)
  1925. archive = await service.get_archive(archive_id)
  1926. if not archive or not archive.timelapse_path:
  1927. raise HTTPException(404, "Timelapse not found")
  1928. timelapse_path = settings.base_dir / archive.timelapse_path
  1929. if not timelapse_path.exists():
  1930. raise HTTPException(404, "Timelapse file not found")
  1931. try:
  1932. processor = TimelapseProcessor(timelapse_path)
  1933. info = await processor.get_info()
  1934. return TimelapseInfoResponse(**info)
  1935. except Exception as e:
  1936. logger.error("Failed to get timelapse info: %s", e)
  1937. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  1938. @router.get("/{archive_id}/timelapse/thumbnails")
  1939. async def get_timelapse_thumbnails(
  1940. archive_id: int,
  1941. count: int = Query(10, ge=1, le=30),
  1942. width: int = Query(160, ge=80, le=320),
  1943. db: AsyncSession = Depends(get_db),
  1944. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1945. ):
  1946. """Generate timeline thumbnail frames for visual scrubbing."""
  1947. import base64
  1948. from backend.app.schemas.timelapse import ThumbnailResponse
  1949. from backend.app.services.timelapse_processor import TimelapseProcessor
  1950. service = ArchiveService(db)
  1951. archive = await service.get_archive(archive_id)
  1952. if not archive or not archive.timelapse_path:
  1953. raise HTTPException(404, "Timelapse not found")
  1954. timelapse_path = settings.base_dir / archive.timelapse_path
  1955. if not timelapse_path.exists():
  1956. raise HTTPException(404, "Timelapse file not found")
  1957. try:
  1958. processor = TimelapseProcessor(timelapse_path)
  1959. thumbnails = await processor.generate_thumbnails(count, width)
  1960. return ThumbnailResponse(
  1961. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1962. timestamps=[ts for ts, _ in thumbnails],
  1963. )
  1964. except Exception as e:
  1965. logger.error("Failed to generate thumbnails: %s", e)
  1966. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1967. @router.post("/{archive_id}/timelapse/process")
  1968. async def process_timelapse(
  1969. archive_id: int,
  1970. trim_start: float = Form(0),
  1971. trim_end: float = Form(None),
  1972. speed: float = Form(1.0),
  1973. save_mode: str = Form("new"),
  1974. output_filename: str = Form(None),
  1975. audio: UploadFile = File(None),
  1976. db: AsyncSession = Depends(get_db),
  1977. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1978. ):
  1979. """Process timelapse with trim, speed, and optional audio overlay."""
  1980. import shutil
  1981. import tempfile
  1982. from backend.app.schemas.timelapse import ProcessResponse
  1983. from backend.app.services.timelapse_processor import TimelapseProcessor
  1984. # Validate speed
  1985. if not 0.25 <= speed <= 4.0:
  1986. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1987. if save_mode not in ("replace", "new"):
  1988. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1989. service = ArchiveService(db)
  1990. archive = await service.get_archive(archive_id)
  1991. if not archive or not archive.timelapse_path:
  1992. raise HTTPException(404, "Timelapse not found")
  1993. timelapse_path = settings.base_dir / archive.timelapse_path
  1994. if not timelapse_path.exists():
  1995. raise HTTPException(404, "Timelapse file not found")
  1996. archive_dir = timelapse_path.parent
  1997. # Handle audio file
  1998. audio_temp_path = None
  1999. if audio and audio.filename:
  2000. # Validate audio file extension
  2001. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  2002. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  2003. audio_content = await audio.read()
  2004. # Extract and validate suffix to prevent path injection
  2005. suffix = Path(audio.filename).suffix.lower()
  2006. if suffix not in (".mp3", ".wav", ".m4a", ".aac", ".ogg"):
  2007. raise HTTPException(400, "Invalid audio file extension")
  2008. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  2009. audio_temp_path.write_bytes(audio_content)
  2010. try:
  2011. processor = TimelapseProcessor(timelapse_path)
  2012. # Determine output path
  2013. if save_mode == "replace":
  2014. # Process to temp file first, then replace
  2015. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  2016. output_path = temp_output
  2017. else:
  2018. # Save as new file alongside original
  2019. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  2020. # Sanitize filename - remove path separators and traversal sequences
  2021. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  2022. # Prevent path traversal
  2023. if ".." in filename or not filename or filename.startswith("."):
  2024. filename = f"timelapse_{archive_id}_edited"
  2025. if not filename.endswith(".mp4"):
  2026. filename += ".mp4"
  2027. output_path = archive_dir / filename # SEC-PATH-OK: filename alnum-filtered + .. rejected above
  2028. success = await processor.process(
  2029. output_path=output_path,
  2030. trim_start=trim_start,
  2031. trim_end=trim_end,
  2032. speed=speed,
  2033. audio_path=audio_temp_path,
  2034. )
  2035. if not success:
  2036. raise HTTPException(500, "Video processing failed")
  2037. # Handle save mode
  2038. if save_mode == "replace":
  2039. # Replace original file
  2040. shutil.move(str(output_path), str(timelapse_path))
  2041. final_path = archive.timelapse_path
  2042. message = "Timelapse replaced successfully"
  2043. else:
  2044. final_path = str(output_path.relative_to(settings.base_dir))
  2045. message = f"Saved as {output_path.name}"
  2046. return ProcessResponse(
  2047. status="completed",
  2048. output_path=final_path,
  2049. message=message,
  2050. )
  2051. except HTTPException:
  2052. raise
  2053. except Exception as e:
  2054. logger.error("Timelapse processing failed: %s", e)
  2055. raise HTTPException(500, f"Processing failed: {str(e)}")
  2056. finally:
  2057. # Cleanup temp audio file
  2058. if audio_temp_path and audio_temp_path.exists():
  2059. audio_temp_path.unlink()
  2060. # ============================================
  2061. # Photo Endpoints
  2062. # ============================================
  2063. @router.post("/{archive_id}/photos")
  2064. async def upload_photo(
  2065. archive_id: int,
  2066. file: UploadFile = File(...),
  2067. db: AsyncSession = Depends(get_db),
  2068. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  2069. ):
  2070. """Upload a photo of the printed result."""
  2071. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2072. archive = result.scalar_one_or_none()
  2073. if not archive:
  2074. raise HTTPException(404, "Archive not found")
  2075. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  2076. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  2077. # Get archive directory
  2078. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2079. photos_dir = archive_dir / "photos"
  2080. photos_dir.mkdir(exist_ok=True)
  2081. # Generate unique filename
  2082. import uuid
  2083. ext = Path(file.filename).suffix.lower()
  2084. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  2085. photo_path = photos_dir / photo_filename # SEC-PATH-OK: photo_filename = uuid.uuid4().hex[:8] + ext
  2086. # Save file
  2087. content = await file.read()
  2088. photo_path.write_bytes(content)
  2089. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  2090. photos = list(archive.photos or [])
  2091. photos.append(photo_filename)
  2092. archive.photos = photos
  2093. await db.commit()
  2094. await db.refresh(archive)
  2095. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  2096. @router.get("/{archive_id}/photos/{filename}")
  2097. async def get_photo(
  2098. archive_id: int,
  2099. filename: str,
  2100. db: AsyncSession = Depends(get_db),
  2101. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2102. ):
  2103. """Get a specific photo.
  2104. Requires a stream token query param (?token=xxx) when auth is enabled.
  2105. """
  2106. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2107. archive = result.scalar_one_or_none()
  2108. if not archive:
  2109. raise HTTPException(404, "Archive not found")
  2110. # Membership check first — UUID-generated names on upload mean any URL
  2111. # filename that doesn't appear here is by definition not a real photo.
  2112. # Mirrors the delete handler below; previously this endpoint had no
  2113. # membership check at all and joined `filename` straight to disk.
  2114. if not archive.photos or filename not in archive.photos:
  2115. raise HTTPException(404, "Photo not found")
  2116. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2117. photos_dir = archive_dir / "photos"
  2118. # Defence-in-depth: even though the membership check above already
  2119. # constrains `filename` to UUID-generated names from upload, the
  2120. # resolve + containment check guards against future code paths that
  2121. # might populate `archive.photos` from a less-trusted source.
  2122. photo_path = safe_join_under(photos_dir, filename)
  2123. if not photo_path.exists():
  2124. raise HTTPException(404, "Photo not found")
  2125. # Determine media type
  2126. ext = Path(filename).suffix.lower()
  2127. media_types = {
  2128. ".jpg": "image/jpeg",
  2129. ".jpeg": "image/jpeg",
  2130. ".png": "image/png",
  2131. ".webp": "image/webp",
  2132. }
  2133. media_type = media_types.get(ext, "image/jpeg")
  2134. return FileResponse(path=photo_path, media_type=media_type)
  2135. @router.delete("/{archive_id}/photos/{filename}")
  2136. async def delete_photo(
  2137. archive_id: int,
  2138. filename: str,
  2139. db: AsyncSession = Depends(get_db),
  2140. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  2141. ):
  2142. """Delete a photo."""
  2143. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2144. archive = result.scalar_one_or_none()
  2145. if not archive:
  2146. raise HTTPException(404, "Archive not found")
  2147. if not archive.photos or filename not in archive.photos:
  2148. raise HTTPException(404, "Photo not found")
  2149. # Delete file — same defence-in-depth as get_photo above.
  2150. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2151. photos_dir = archive_dir / "photos"
  2152. photo_path = safe_join_under(photos_dir, filename)
  2153. if photo_path.exists():
  2154. photo_path.unlink()
  2155. # Update archive photos list
  2156. photos = [p for p in archive.photos if p != filename]
  2157. archive.photos = photos if photos else None
  2158. await db.commit()
  2159. return {"status": "deleted", "photos": archive.photos}
  2160. # ============================================
  2161. # QR Code Endpoint
  2162. # ============================================
  2163. @router.get("/{archive_id}/qrcode")
  2164. async def get_qrcode(
  2165. archive_id: int,
  2166. request: Request,
  2167. size: int = 200,
  2168. db: AsyncSession = Depends(get_db),
  2169. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2170. ):
  2171. """Generate a QR code that links to this archive.
  2172. Requires a stream token query param (?token=xxx) when auth is enabled.
  2173. """
  2174. try:
  2175. import qrcode
  2176. from PIL import Image as PILImage
  2177. except ImportError:
  2178. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  2179. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2180. archive = result.scalar_one_or_none()
  2181. if not archive:
  2182. raise HTTPException(404, "Archive not found")
  2183. # Build URL to archive download
  2184. base_url = str(request.base_url).rstrip("/")
  2185. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  2186. # Generate QR code
  2187. qr = qrcode.QRCode(
  2188. version=1,
  2189. error_correction=qrcode.constants.ERROR_CORRECT_M,
  2190. box_size=10,
  2191. border=2,
  2192. )
  2193. qr.add_data(archive_url)
  2194. qr.make(fit=True)
  2195. img = qr.make_image(fill_color="black", back_color="white")
  2196. # Convert to PIL Image for resizing
  2197. pil_img = img.get_image()
  2198. # Resize if needed
  2199. if size != 200:
  2200. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  2201. # Convert to bytes
  2202. buffer = io.BytesIO()
  2203. pil_img.save(buffer, format="PNG")
  2204. buffer.seek(0)
  2205. qr_filename = f"qr_{archive.print_name or archive_id}.png"
  2206. return Response(
  2207. content=buffer.getvalue(),
  2208. media_type="image/png",
  2209. headers={"Content-Disposition": build_content_disposition(qr_filename, disposition="inline")},
  2210. )
  2211. @router.get("/{archive_id}/capabilities")
  2212. async def get_archive_capabilities(
  2213. archive_id: int,
  2214. db: AsyncSession = Depends(get_db),
  2215. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2216. ):
  2217. """Check what viewing capabilities are available for this 3MF file."""
  2218. import defusedxml.ElementTree as ET
  2219. service = ArchiveService(db)
  2220. archive = await service.get_archive(archive_id)
  2221. if not archive:
  2222. raise HTTPException(404, "Archive not found")
  2223. file_path = settings.base_dir / archive.file_path
  2224. if not file_path.is_file():
  2225. raise HTTPException(404, "File not found")
  2226. has_model = False
  2227. has_gcode = False
  2228. has_source = False
  2229. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  2230. filament_colors: list[str] = []
  2231. # Check if source 3MF exists - this is where actual mesh data typically lives
  2232. source_path = None
  2233. if archive.source_3mf_path:
  2234. source_path = settings.base_dir / archive.source_3mf_path
  2235. if source_path.exists():
  2236. has_source = True
  2237. # Helper function to check for mesh data and extract colors from a 3MF file
  2238. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  2239. """Extract mesh presence, colors, and build volume from a 3MF file."""
  2240. found_mesh = False
  2241. colors: list[str] = []
  2242. volume = {"x": 256, "y": 256, "z": 256}
  2243. try:
  2244. with zipfile.ZipFile(zf_path, "r") as zf:
  2245. names = zf.namelist()
  2246. # Check for 3D model - look for actual mesh data
  2247. for name in names:
  2248. if name.endswith(".model"):
  2249. try:
  2250. content = zf.read(name).decode("utf-8")
  2251. if "<vertex" in content or "<mesh" in content:
  2252. found_mesh = True
  2253. break
  2254. except Exception:
  2255. pass # Skip unreadable .model entries in archive
  2256. # Extract filament colors from project_settings.config
  2257. if "Metadata/project_settings.config" in names:
  2258. try:
  2259. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  2260. config_data = json.loads(config_content)
  2261. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  2262. printable_area = config_data.get("printable_area", [])
  2263. if printable_area and len(printable_area) >= 3:
  2264. max_x = 0
  2265. max_y = 0
  2266. for coord in printable_area:
  2267. if "x" in coord:
  2268. parts = coord.split("x")
  2269. if len(parts) == 2:
  2270. try:
  2271. x, y = int(parts[0]), int(parts[1])
  2272. max_x = max(max_x, x)
  2273. max_y = max(max_y, y)
  2274. except ValueError:
  2275. pass # Skip non-numeric printable_area coordinate
  2276. if max_x > 0 and max_y > 0:
  2277. volume["x"] = max_x
  2278. volume["y"] = max_y
  2279. # Parse printable_height
  2280. printable_height = config_data.get("printable_height")
  2281. if printable_height:
  2282. try:
  2283. volume["z"] = int(printable_height)
  2284. except (ValueError, TypeError):
  2285. pass # Skip unparseable printable_height value
  2286. # Extract filament colors
  2287. raw_colors = config_data.get("filament_colour", [])
  2288. if raw_colors:
  2289. for color in raw_colors:
  2290. if color and isinstance(color, str):
  2291. colors.append(color)
  2292. except Exception:
  2293. pass # Skip malformed project_settings.config
  2294. except zipfile.BadZipFile:
  2295. pass # File is not a valid zip/3MF archive
  2296. return found_mesh, colors, volume
  2297. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  2298. if has_source and source_path:
  2299. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  2300. if source_has_mesh:
  2301. has_model = True
  2302. if source_colors:
  2303. filament_colors = source_colors
  2304. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  2305. build_volume = source_volume
  2306. try:
  2307. with zipfile.ZipFile(file_path, "r") as zf:
  2308. names = zf.namelist()
  2309. # Check for G-code in the sliced file
  2310. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  2311. # Check for 3D model in sliced file (fallback if no source)
  2312. if not has_model:
  2313. for name in names:
  2314. if name.endswith(".model"):
  2315. try:
  2316. content = zf.read(name).decode("utf-8")
  2317. if "<vertex" in content or "<mesh" in content:
  2318. has_model = True
  2319. break
  2320. except Exception:
  2321. pass # Skip unreadable .model entries in archive
  2322. # Extract filament colors from slice_info.config (for gcode preview)
  2323. # These are the actual filaments used in the print, indexed by tool/extruder
  2324. slice_colors: list[str] = []
  2325. if "Metadata/slice_info.config" in names:
  2326. try:
  2327. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  2328. root = ET.fromstring(slice_content)
  2329. filaments = root.findall(".//filament")
  2330. filament_map: dict[int, str] = {}
  2331. for f in filaments:
  2332. fid = f.get("id")
  2333. fcolor = f.get("color")
  2334. used_g = f.get("used_g", "0")
  2335. try:
  2336. used_amount = float(used_g)
  2337. except (ValueError, TypeError):
  2338. used_amount = 0
  2339. if fid is not None and fcolor:
  2340. try:
  2341. tool_id = int(fid) - 1
  2342. if tool_id >= 0 and used_amount > 0:
  2343. filament_map[tool_id] = fcolor
  2344. except ValueError:
  2345. pass # Skip filament entry with non-numeric ID
  2346. if filament_map:
  2347. max_tool = max(filament_map.keys())
  2348. for i in range(max_tool + 1):
  2349. slice_colors.append(filament_map.get(i, "#00AE42"))
  2350. except Exception:
  2351. pass # Skip malformed slice_info.config XML
  2352. # Use slice_info colors if we don't have colors from source yet
  2353. if not filament_colors and slice_colors:
  2354. filament_colors = slice_colors
  2355. # Extract build volume from sliced file if not already set from source
  2356. if build_volume["x"] == 256 and build_volume["y"] == 256:
  2357. if "Metadata/project_settings.config" in names:
  2358. try:
  2359. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  2360. config_data = json.loads(config_content)
  2361. printable_area = config_data.get("printable_area", [])
  2362. if printable_area and len(printable_area) >= 3:
  2363. max_x = 0
  2364. max_y = 0
  2365. for coord in printable_area:
  2366. if "x" in coord:
  2367. parts = coord.split("x")
  2368. if len(parts) == 2:
  2369. try:
  2370. x, y = int(parts[0]), int(parts[1])
  2371. max_x = max(max_x, x)
  2372. max_y = max(max_y, y)
  2373. except ValueError:
  2374. pass # Skip non-numeric printable_area coordinate
  2375. if max_x > 0 and max_y > 0:
  2376. build_volume["x"] = max_x
  2377. build_volume["y"] = max_y
  2378. printable_height = config_data.get("printable_height")
  2379. if printable_height:
  2380. try:
  2381. build_volume["z"] = int(printable_height)
  2382. except (ValueError, TypeError):
  2383. pass # Skip unparseable printable_height value
  2384. # Fallback colors from project_settings if still empty
  2385. if not filament_colors:
  2386. raw_colors = config_data.get("filament_colour", [])
  2387. if raw_colors:
  2388. for color in raw_colors:
  2389. if color and isinstance(color, str):
  2390. filament_colors.append(color)
  2391. except Exception:
  2392. pass # Skip malformed project_settings.config
  2393. except zipfile.BadZipFile:
  2394. raise HTTPException(400, "Invalid 3MF file")
  2395. return {
  2396. "has_model": has_model,
  2397. "has_gcode": has_gcode,
  2398. "has_source": has_source,
  2399. "build_volume": build_volume,
  2400. "filament_colors": filament_colors,
  2401. }
  2402. @router.get("/{archive_id}/gcode")
  2403. async def get_gcode(
  2404. archive_id: int,
  2405. plate: int | None = None,
  2406. db: AsyncSession = Depends(get_db),
  2407. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2408. ):
  2409. """Extract and return G-code from the 3MF file.
  2410. When *plate* is provided, returns the G-code for that specific plate
  2411. (e.g. ``?plate=2`` returns ``Metadata/plate_2.gcode``). If omitted, falls
  2412. back to the first plate found in the archive (preserving the original
  2413. behaviour for callers that predate the multi-plate viewer).
  2414. """
  2415. service = ArchiveService(db)
  2416. archive = await service.get_archive(archive_id)
  2417. if not archive:
  2418. raise HTTPException(404, "Archive not found")
  2419. file_path = settings.base_dir / archive.file_path
  2420. if not file_path.is_file():
  2421. raise HTTPException(404, "File not found")
  2422. if plate is not None and plate < 1:
  2423. raise HTTPException(400, "Plate index must be >= 1")
  2424. try:
  2425. with zipfile.ZipFile(file_path, "r") as zf:
  2426. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  2427. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  2428. if not gcode_files:
  2429. raise HTTPException(
  2430. 404,
  2431. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  2432. )
  2433. if plate is not None:
  2434. # Resolve plate → filename via the same parsing the plates
  2435. # endpoint uses (int() on the suffix), so zero-padded names
  2436. # like plate_01.gcode are found when the plates endpoint
  2437. # reported index 1.
  2438. selected = None
  2439. for gf in gcode_files:
  2440. if not gf.startswith("Metadata/plate_"):
  2441. continue
  2442. suffix = gf[len("Metadata/plate_") : -len(".gcode")]
  2443. try:
  2444. if int(suffix) == plate:
  2445. selected = gf
  2446. break
  2447. except ValueError:
  2448. continue
  2449. if selected is None:
  2450. raise HTTPException(404, f"Plate {plate} not found in this archive")
  2451. else:
  2452. selected = gcode_files[0]
  2453. gcode_content = zf.read(selected).decode("utf-8")
  2454. return Response(content=gcode_content, media_type="text/plain")
  2455. except zipfile.BadZipFile:
  2456. raise HTTPException(400, "Invalid 3MF file")
  2457. except HTTPException:
  2458. raise
  2459. except Exception as e:
  2460. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  2461. @router.get("/{archive_id}/plate-preview")
  2462. async def get_plate_preview(
  2463. archive_id: int,
  2464. db: AsyncSession = Depends(get_db),
  2465. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2466. ):
  2467. """Get the plate preview image from the 3MF file.
  2468. Returns the slicer-generated plate thumbnail which shows the model
  2469. with correct colors and positioning.
  2470. Requires a stream token query param (?token=xxx) when auth is enabled.
  2471. """
  2472. service = ArchiveService(db)
  2473. archive = await service.get_archive(archive_id)
  2474. if not archive:
  2475. raise HTTPException(404, "Archive not found")
  2476. file_path = settings.base_dir / archive.file_path
  2477. if not file_path.is_file():
  2478. raise HTTPException(404, "File not found")
  2479. try:
  2480. with zipfile.ZipFile(file_path, "r") as zf:
  2481. names = zf.namelist()
  2482. # Try to find plate preview images in order of preference
  2483. # First look for the specific plate being printed (check slice_info for plate index)
  2484. plate_num = 1
  2485. if "Metadata/slice_info.config" in names:
  2486. try:
  2487. import defusedxml.ElementTree as ET
  2488. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  2489. root = ET.fromstring(slice_content)
  2490. plate_elem = root.find(".//plate/metadata[@key='index']")
  2491. if plate_elem is not None:
  2492. plate_num = int(plate_elem.get("value", "1"))
  2493. except Exception:
  2494. pass # Default plate_num=1 if slice_info is missing or malformed
  2495. # Try plate-specific image first, then fall back to plate_1
  2496. preview_paths = [
  2497. f"Metadata/plate_{plate_num}.png",
  2498. "Metadata/plate_1.png",
  2499. "Metadata/thumbnail.png",
  2500. ]
  2501. for preview_path in preview_paths:
  2502. if preview_path in names:
  2503. image_data = zf.read(preview_path)
  2504. return Response(content=image_data, media_type="image/png")
  2505. # If no plate image, try any PNG in Metadata
  2506. for name in names:
  2507. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  2508. image_data = zf.read(name)
  2509. return Response(content=image_data, media_type="image/png")
  2510. raise HTTPException(404, "No plate preview found in 3MF file")
  2511. except zipfile.BadZipFile:
  2512. raise HTTPException(400, "Invalid 3MF file")
  2513. except HTTPException:
  2514. raise
  2515. except Exception as e:
  2516. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  2517. @router.post("/upload")
  2518. async def upload_archive(
  2519. file: UploadFile = File(...),
  2520. printer_id: int | None = None,
  2521. db: AsyncSession = Depends(get_db),
  2522. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  2523. ):
  2524. """Manually upload a 3MF file to archive."""
  2525. if not file.filename or not file.filename.endswith(".3mf"):
  2526. raise HTTPException(400, "File must be a .3mf file")
  2527. # Save uploaded file temporarily — strip directory components to prevent path traversal
  2528. safe_filename = _safe_filename(file.filename)
  2529. temp_path = (
  2530. settings.archive_dir / "temp" / safe_filename
  2531. ) # SEC-PATH-OK: safe_filename = _safe_filename(...) basename-stripped above
  2532. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2533. try:
  2534. content = await file.read()
  2535. # #1401: same content validation as library upload — catches
  2536. # raw-gcode-renamed-to-.3mf and other unprintable shapes before
  2537. # archiving them and offering them up for print.
  2538. from backend.app.api.routes.library import validate_print_file_upload
  2539. validate_print_file_upload(file.filename, content)
  2540. temp_path.write_bytes(content)
  2541. service = ArchiveService(db)
  2542. archive = await service.archive_print(
  2543. printer_id=printer_id,
  2544. source_file=temp_path,
  2545. created_by_id=current_user.id if current_user else None,
  2546. )
  2547. if not archive:
  2548. raise HTTPException(400, "Failed to archive file")
  2549. return ArchiveResponse.model_validate(archive)
  2550. finally:
  2551. if temp_path.exists():
  2552. temp_path.unlink()
  2553. @router.post("/upload-bulk")
  2554. async def upload_archives_bulk(
  2555. files: list[UploadFile] = File(...),
  2556. printer_id: int | None = None,
  2557. db: AsyncSession = Depends(get_db),
  2558. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  2559. ):
  2560. """Bulk upload multiple 3MF files to archive."""
  2561. from backend.app.api.routes.library import validate_print_file_upload
  2562. results = []
  2563. errors = []
  2564. for file in files:
  2565. if not file.filename or not file.filename.endswith(".3mf"):
  2566. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  2567. continue
  2568. safe_filename = _safe_filename(file.filename)
  2569. temp_path = (
  2570. settings.archive_dir / "temp" / safe_filename
  2571. ) # SEC-PATH-OK: safe_filename = _safe_filename(...) basename-stripped above
  2572. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2573. try:
  2574. content = await file.read()
  2575. # #1401: bulk-upload variant of the library validation. Collect
  2576. # the rejection per-file rather than aborting the whole batch
  2577. # so one bad file in a 10-file drag-drop doesn't lose the
  2578. # other nine.
  2579. try:
  2580. validate_print_file_upload(file.filename, content)
  2581. except HTTPException as exc:
  2582. errors.append({"filename": file.filename, "error": exc.detail})
  2583. continue
  2584. temp_path.write_bytes(content)
  2585. service = ArchiveService(db)
  2586. archive = await service.archive_print(
  2587. printer_id=printer_id,
  2588. source_file=temp_path,
  2589. created_by_id=current_user.id if current_user else None,
  2590. )
  2591. if archive:
  2592. results.append(
  2593. {
  2594. "filename": file.filename,
  2595. "id": archive.id,
  2596. "status": "success",
  2597. }
  2598. )
  2599. else:
  2600. errors.append({"filename": file.filename, "error": "Failed to process"})
  2601. except Exception as e:
  2602. logger.exception("Failed to upload archive %s: %s", file.filename, e)
  2603. errors.append({"filename": file.filename, "error": "Failed to process file"})
  2604. finally:
  2605. if temp_path.exists():
  2606. temp_path.unlink()
  2607. return {
  2608. "uploaded": len(results),
  2609. "failed": len(errors),
  2610. "results": results,
  2611. "errors": errors,
  2612. }
  2613. @router.get("/{archive_id}/plates")
  2614. async def get_archive_plates(
  2615. archive_id: int,
  2616. db: AsyncSession = Depends(get_db),
  2617. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2618. ):
  2619. """Get available plates from a multi-plate 3MF archive.
  2620. Returns a list of plates with their index, name, thumbnail availability,
  2621. and filament requirements. For single-plate exports, returns a single plate.
  2622. """
  2623. import re
  2624. import defusedxml.ElementTree as ET
  2625. service = ArchiveService(db)
  2626. archive = await service.get_archive(archive_id)
  2627. if not archive:
  2628. raise HTTPException(404, "Archive not found")
  2629. file_path = settings.base_dir / archive.file_path
  2630. if not file_path.is_file():
  2631. raise HTTPException(404, "Archive file not found")
  2632. plates = []
  2633. # Initialize so the `has_gcode = bool(gcode_files)` after the try/except
  2634. # never raises NameError when the archive isn't a valid zip (e.g. plain
  2635. # .gcode file from a sliced-archive flow that didn't request 3MF output).
  2636. gcode_files: list[str] = []
  2637. # Printer / process preset names the 3MF was prepared with — used by the
  2638. # SliceModal to default its dropdowns (#1325).
  2639. embedded_presets: dict[str, str | None] = {"printer": None, "process": None}
  2640. try:
  2641. with zipfile.ZipFile(file_path, "r") as zf:
  2642. namelist = zf.namelist()
  2643. embedded_presets = extract_embedded_presets_from_3mf(zf)
  2644. # Find all plate gcode files to determine available plates
  2645. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  2646. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  2647. plate_indices: list[int] = []
  2648. if gcode_files:
  2649. # Extract plate indices from gcode filenames
  2650. for gf in gcode_files:
  2651. # "Metadata/plate_5.gcode" -> 5
  2652. try:
  2653. # Remove "Metadata/plate_" and ".gcode"
  2654. plate_str = gf[15:-6]
  2655. plate_indices.append(int(plate_str))
  2656. except ValueError:
  2657. pass # Skip gcode file with non-numeric plate index
  2658. else:
  2659. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  2660. plate_png_files = [
  2661. n
  2662. for n in namelist
  2663. if n.startswith("Metadata/plate_")
  2664. and n.endswith(".png")
  2665. and "_small" not in n
  2666. and "no_light" not in n
  2667. ]
  2668. plate_name_candidates = plate_json_files + plate_png_files
  2669. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  2670. seen_indices: set[int] = set()
  2671. for name in plate_name_candidates:
  2672. match = plate_re.match(name)
  2673. if match:
  2674. try:
  2675. index = int(match.group(1))
  2676. except ValueError:
  2677. continue
  2678. if index in seen_indices:
  2679. continue
  2680. seen_indices.add(index)
  2681. plate_indices.append(index)
  2682. if not plate_indices:
  2683. # No plate metadata found
  2684. return {
  2685. "archive_id": archive_id,
  2686. "filename": archive.filename,
  2687. "plates": [],
  2688. "is_multi_plate": False,
  2689. }
  2690. plate_indices.sort()
  2691. # Parse model_settings.config for plate names + object assignments
  2692. # Plate names are stored with plater_id and plater_name keys
  2693. plate_names = {} # plater_id -> name
  2694. plate_object_ids: dict[int, list[str]] = {}
  2695. object_names_by_id: dict[str, str] = {}
  2696. if "Metadata/model_settings.config" in namelist:
  2697. try:
  2698. model_content = zf.read("Metadata/model_settings.config").decode()
  2699. model_root = ET.fromstring(model_content)
  2700. # Build object ID -> name map
  2701. for obj_elem in model_root.findall(".//object"):
  2702. obj_id = obj_elem.get("id")
  2703. if not obj_id:
  2704. continue
  2705. name_meta = obj_elem.find("metadata[@key='name']")
  2706. obj_name = name_meta.get("value") if name_meta is not None else None
  2707. if obj_name:
  2708. object_names_by_id[obj_id] = obj_name
  2709. for plate_elem in model_root.findall(".//plate"):
  2710. plater_id = None
  2711. plater_name = None
  2712. for meta in plate_elem.findall("metadata"):
  2713. key = meta.get("key")
  2714. value = meta.get("value")
  2715. if key == "plater_id" and value:
  2716. try:
  2717. plater_id = int(value)
  2718. except ValueError:
  2719. pass # Skip plate with non-numeric plater_id
  2720. elif key == "plater_name" and value:
  2721. plater_name = value.strip()
  2722. if plater_id is not None and plater_name:
  2723. plate_names[plater_id] = plater_name
  2724. if plater_id is not None:
  2725. for instance_elem in plate_elem.findall("model_instance"):
  2726. for inst_meta in instance_elem.findall("metadata"):
  2727. if inst_meta.get("key") == "object_id":
  2728. obj_id = inst_meta.get("value")
  2729. if not obj_id:
  2730. continue
  2731. plate_object_ids.setdefault(plater_id, [])
  2732. if obj_id not in plate_object_ids[plater_id]:
  2733. plate_object_ids[plater_id].append(obj_id)
  2734. except Exception:
  2735. pass # model_settings.config parsing is optional
  2736. # Parse slice_info.config for plate metadata
  2737. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  2738. if "Metadata/slice_info.config" in namelist:
  2739. content = zf.read("Metadata/slice_info.config").decode()
  2740. root = ET.fromstring(content)
  2741. for plate_elem in root.findall(".//plate"):
  2742. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  2743. # Get plate index from metadata
  2744. plate_index = None
  2745. for meta in plate_elem.findall("metadata"):
  2746. key = meta.get("key")
  2747. value = meta.get("value")
  2748. if key == "index" and value:
  2749. try:
  2750. plate_index = int(value)
  2751. except ValueError:
  2752. pass # Skip plate with non-numeric index
  2753. elif key == "prediction" and value:
  2754. try:
  2755. plate_info["prediction"] = int(value)
  2756. except ValueError:
  2757. pass # Skip non-numeric print time prediction
  2758. elif key == "weight" and value:
  2759. try:
  2760. plate_info["weight"] = float(value)
  2761. except ValueError:
  2762. pass # Skip non-numeric filament weight
  2763. # Get filaments used in this plate
  2764. for filament_elem in plate_elem.findall("filament"):
  2765. filament_id = filament_elem.get("id")
  2766. filament_type = filament_elem.get("type", "")
  2767. filament_color = filament_elem.get("color", "")
  2768. used_g = filament_elem.get("used_g", "0")
  2769. used_m = filament_elem.get("used_m", "0")
  2770. try:
  2771. used_grams = float(used_g)
  2772. except (ValueError, TypeError):
  2773. used_grams = 0
  2774. if used_grams > 0 and filament_id:
  2775. plate_info["filaments"].append(
  2776. {
  2777. "slot_id": int(filament_id),
  2778. "type": filament_type,
  2779. "color": filament_color,
  2780. "used_grams": round(used_grams, 1),
  2781. "used_meters": float(used_m) if used_m else 0,
  2782. }
  2783. )
  2784. # Sort filaments by slot ID
  2785. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  2786. # Collect all object names on this plate
  2787. for obj_elem in plate_elem.findall("object"):
  2788. obj_name = obj_elem.get("name")
  2789. if obj_name and obj_name not in plate_info["objects"]:
  2790. plate_info["objects"].append(obj_name)
  2791. # Set plate name: prefer custom name from model_settings.config,
  2792. # fall back to first object name if no custom name was set
  2793. if plate_index is not None:
  2794. custom_name = plate_names.get(plate_index)
  2795. if custom_name:
  2796. plate_info["name"] = custom_name
  2797. else:
  2798. # Fall back to first object name as hint
  2799. if plate_info["objects"]:
  2800. plate_info["name"] = plate_info["objects"][0]
  2801. plate_metadata[plate_index] = plate_info
  2802. # Parse plate_*.json for object lists when slice_info is missing
  2803. plate_json_objects: dict[int, list[str]] = {}
  2804. for name in namelist:
  2805. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  2806. if not match:
  2807. continue
  2808. try:
  2809. plate_index = int(match.group(1))
  2810. except ValueError:
  2811. continue
  2812. try:
  2813. payload = json.loads(zf.read(name).decode())
  2814. bbox_objects = payload.get("bbox_objects", [])
  2815. names = []
  2816. for obj in bbox_objects:
  2817. obj_name = obj.get("name") if isinstance(obj, dict) else None
  2818. if obj_name and obj_name not in names:
  2819. names.append(obj_name)
  2820. if names:
  2821. plate_json_objects[plate_index] = names
  2822. except Exception:
  2823. continue
  2824. # Build plate list
  2825. for idx in plate_indices:
  2826. meta = plate_metadata.get(idx, {})
  2827. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  2828. objects = meta.get("objects", [])
  2829. if not objects:
  2830. objects = plate_json_objects.get(idx, [])
  2831. if not objects and plate_object_ids.get(idx):
  2832. objects = [
  2833. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  2834. ]
  2835. plate_name = meta.get("name")
  2836. if not plate_name:
  2837. plate_name = plate_names.get(idx)
  2838. if not plate_name and objects:
  2839. plate_name = objects[0]
  2840. plates.append(
  2841. {
  2842. "index": idx,
  2843. "name": plate_name,
  2844. "objects": objects,
  2845. "object_count": len(objects),
  2846. "has_thumbnail": has_thumbnail,
  2847. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  2848. if has_thumbnail
  2849. else None,
  2850. "print_time_seconds": meta.get("prediction"),
  2851. "filament_used_grams": meta.get("weight"),
  2852. "filaments": meta.get("filaments", []),
  2853. }
  2854. )
  2855. except Exception as e:
  2856. logger.warning("Failed to parse plates from archive %s: %s", archive_id, e)
  2857. # Has gcode iff the plate list was built from .gcode filenames (as opposed
  2858. # to the JSON/PNG fallback for source-only 3MF projects). Callers that need
  2859. # to preview gcode — the viewer, skip-objects — can gate on this instead of
  2860. # 404-ing on every plate request.
  2861. has_gcode = bool(gcode_files)
  2862. return {
  2863. "archive_id": archive_id,
  2864. "filename": archive.filename,
  2865. "plates": plates,
  2866. "is_multi_plate": len(plates) > 1,
  2867. "has_gcode": has_gcode,
  2868. "embedded_printer": embedded_presets["printer"],
  2869. "embedded_process": embedded_presets["process"],
  2870. }
  2871. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  2872. async def get_plate_thumbnail(
  2873. archive_id: int,
  2874. plate_index: int,
  2875. db: AsyncSession = Depends(get_db),
  2876. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2877. ):
  2878. """Get the thumbnail image for a specific plate.
  2879. Requires a stream token query param (?token=xxx) when auth is enabled.
  2880. """
  2881. service = ArchiveService(db)
  2882. archive = await service.get_archive(archive_id)
  2883. if not archive:
  2884. raise HTTPException(404, "Archive not found")
  2885. file_path = settings.base_dir / archive.file_path
  2886. if not file_path.is_file():
  2887. raise HTTPException(404, "Archive file not found")
  2888. try:
  2889. with zipfile.ZipFile(file_path, "r") as zf:
  2890. thumb_path = f"Metadata/plate_{plate_index}.png"
  2891. if thumb_path in zf.namelist():
  2892. data = zf.read(thumb_path)
  2893. return Response(content=data, media_type="image/png")
  2894. except Exception:
  2895. pass # Fall through to 404 if archive is unreadable or thumbnail missing
  2896. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  2897. async def _try_preview_slice_filaments(
  2898. db: AsyncSession,
  2899. *,
  2900. kind: str,
  2901. source_id: int,
  2902. plate_id: int,
  2903. file_path: Path,
  2904. request_id: str | None = None,
  2905. bundle_id: str | None = None,
  2906. printer_name: str | None = None,
  2907. process_name: str | None = None,
  2908. filament_names: list[str] | None = None,
  2909. ) -> list[dict] | None:
  2910. """Run a preview slice via the user's configured sidecar so the filament
  2911. list endpoint can return real per-plate filaments for unsliced project
  2912. files. Returns ``None`` on any failure — the caller falls back to the
  2913. painted-face heuristic. ``request_id`` flows through to the sidecar
  2914. for live progress on the SliceModal's inline spinner + toast.
  2915. Bundle context (id + preset names) is forwarded to the preview helper
  2916. so the preview can mirror the real-print profile triplet when supplied
  2917. — see ``slice_preview.get_preview_filaments`` for the full contract.
  2918. """
  2919. from backend.app.api.routes.settings import get_setting
  2920. from backend.app.services.slice_preview import get_preview_filaments
  2921. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  2922. if preferred == "orcaslicer":
  2923. configured = await get_setting(db, "orcaslicer_api_url")
  2924. api_url = (configured or settings.slicer_api_url).strip()
  2925. elif preferred == "bambu_studio":
  2926. configured = await get_setting(db, "bambu_studio_api_url")
  2927. api_url = (configured or settings.bambu_studio_api_url).strip()
  2928. else:
  2929. return None
  2930. if not api_url:
  2931. return None
  2932. try:
  2933. file_bytes = file_path.read_bytes()
  2934. except OSError:
  2935. return None
  2936. return await get_preview_filaments(
  2937. kind=kind,
  2938. source_id=source_id,
  2939. plate_id=plate_id,
  2940. file_bytes=file_bytes,
  2941. file_name=file_path.name,
  2942. api_url=api_url,
  2943. request_id=request_id,
  2944. bundle_id=bundle_id,
  2945. printer_name=printer_name,
  2946. process_name=process_name,
  2947. filament_names=filament_names,
  2948. )
  2949. @router.get("/{archive_id}/filament-requirements")
  2950. async def get_filament_requirements(
  2951. archive_id: int,
  2952. plate_id: int | None = None,
  2953. request_id: str | None = None,
  2954. bundle_id: str | None = None,
  2955. printer_name: str | None = None,
  2956. process_name: str | None = None,
  2957. filament_names: str | None = None,
  2958. db: AsyncSession = Depends(get_db),
  2959. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2960. ):
  2961. """Get filament requirements from the archived 3MF file.
  2962. Returns the filaments used in this print with their slot IDs, types, colors,
  2963. and usage amounts. This can be compared with current AMS state before reprinting.
  2964. Args:
  2965. archive_id: The archive ID
  2966. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  2967. bundle_id / printer_name / process_name / filament_names: Optional
  2968. bundle context. When all four are supplied, the preview slice
  2969. (run for unsliced project files) uses ``slice_with_bundle``
  2970. against the named preset triplet instead of the embedded-
  2971. settings fallback. ``filament_names`` is comma- or semicolon-
  2972. separated.
  2973. """
  2974. import defusedxml.ElementTree as ET
  2975. service = ArchiveService(db)
  2976. archive = await service.get_archive(archive_id)
  2977. if not archive:
  2978. raise HTTPException(404, "Archive not found")
  2979. file_path = settings.base_dir / archive.file_path
  2980. if not file_path.is_file():
  2981. raise HTTPException(404, "Archive file not found")
  2982. filaments = []
  2983. try:
  2984. with zipfile.ZipFile(file_path, "r") as zf:
  2985. # Parse slice_info.config for filament requirements
  2986. if "Metadata/slice_info.config" in zf.namelist():
  2987. content = zf.read("Metadata/slice_info.config").decode()
  2988. root = ET.fromstring(content)
  2989. # If plate_id is specified, find filaments for that specific plate
  2990. if plate_id is not None:
  2991. # Find the plate element with matching index
  2992. for plate_elem in root.findall(".//plate"):
  2993. plate_index = None
  2994. for meta in plate_elem.findall("metadata"):
  2995. if meta.get("key") == "index":
  2996. try:
  2997. plate_index = int(meta.get("value", "0"))
  2998. except ValueError:
  2999. pass # Skip plate with non-numeric index metadata
  3000. break
  3001. if plate_index == plate_id:
  3002. # Extract filaments from this plate element
  3003. for filament_elem in plate_elem.findall("filament"):
  3004. filament_id = filament_elem.get("id")
  3005. filament_type = filament_elem.get("type", "")
  3006. filament_color = filament_elem.get("color", "")
  3007. used_g = filament_elem.get("used_g", "0")
  3008. used_m = filament_elem.get("used_m", "0")
  3009. tray_info_idx = filament_elem.get("tray_info_idx", "")
  3010. try:
  3011. used_grams = float(used_g)
  3012. except (ValueError, TypeError):
  3013. used_grams = 0
  3014. if used_grams > 0 and filament_id:
  3015. filaments.append(
  3016. {
  3017. "slot_id": int(filament_id),
  3018. "type": filament_type,
  3019. "color": filament_color,
  3020. "used_grams": round(used_grams, 1),
  3021. "used_meters": float(used_m) if used_m else 0,
  3022. "tray_info_idx": tray_info_idx,
  3023. "used_in_plate": True,
  3024. }
  3025. )
  3026. break
  3027. else:
  3028. # No plate_id specified - extract all filaments with used_g > 0
  3029. # This is the legacy behavior for single-plate files
  3030. for filament_elem in root.findall(".//filament"):
  3031. filament_id = filament_elem.get("id")
  3032. filament_type = filament_elem.get("type", "")
  3033. filament_color = filament_elem.get("color", "")
  3034. used_g = filament_elem.get("used_g", "0")
  3035. used_m = filament_elem.get("used_m", "0")
  3036. tray_info_idx = filament_elem.get("tray_info_idx", "")
  3037. # Only include filaments that are actually used
  3038. try:
  3039. used_grams = float(used_g)
  3040. except (ValueError, TypeError):
  3041. used_grams = 0
  3042. if used_grams > 0 and filament_id:
  3043. filaments.append(
  3044. {
  3045. "slot_id": int(filament_id),
  3046. "type": filament_type,
  3047. "color": filament_color,
  3048. "used_grams": round(used_grams, 1),
  3049. "used_meters": float(used_m) if used_m else 0,
  3050. "tray_info_idx": tray_info_idx,
  3051. "used_in_plate": True,
  3052. }
  3053. )
  3054. # Unsliced project files: see library.py for full rationale.
  3055. # Return the FULL project_settings.config slot list with a
  3056. # used_in_plate flag derived from the preview slice; the
  3057. # CLI needs every slot pre-filled to avoid silent default
  3058. # substitution.
  3059. if not filaments:
  3060. project_filaments = extract_project_filaments_from_3mf(zf)
  3061. used_slot_ids: set[int] = set()
  3062. if project_filaments and plate_id is not None:
  3063. parsed_filament_names: list[str] | None = None
  3064. if filament_names:
  3065. parsed_filament_names = [
  3066. n.strip() for n in filament_names.replace(";", ",").split(",") if n.strip()
  3067. ] or None
  3068. preview = await _try_preview_slice_filaments(
  3069. db,
  3070. kind="archive",
  3071. source_id=archive_id,
  3072. plate_id=plate_id,
  3073. file_path=file_path,
  3074. request_id=request_id,
  3075. bundle_id=bundle_id,
  3076. printer_name=printer_name,
  3077. process_name=process_name,
  3078. filament_names=parsed_filament_names,
  3079. )
  3080. if preview is not None:
  3081. used_slot_ids = {f["slot_id"] for f in preview}
  3082. fallback_all_used = not used_slot_ids
  3083. for f in project_filaments:
  3084. f["used_in_plate"] = fallback_all_used or f["slot_id"] in used_slot_ids
  3085. filaments = project_filaments
  3086. # Sort by slot ID
  3087. filaments.sort(key=lambda x: x["slot_id"])
  3088. # Enrich with nozzle mapping for dual-nozzle printers
  3089. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  3090. if nozzle_mapping:
  3091. for filament in filaments:
  3092. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  3093. except Exception as e:
  3094. logger.warning("Failed to parse filament requirements from archive %s: %s", archive_id, e)
  3095. return {
  3096. "archive_id": archive_id,
  3097. "filename": archive.filename,
  3098. "plate_id": plate_id,
  3099. "filaments": filaments,
  3100. }
  3101. @router.post("/{archive_id}/slice", status_code=202)
  3102. async def slice_archive(
  3103. archive_id: int,
  3104. request: SliceRequest,
  3105. db: AsyncSession = Depends(get_db),
  3106. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  3107. ):
  3108. """Enqueue a slice job for an archive's source. Returns 202 + job_id;
  3109. the slice runs in the background, the caller polls `GET /slice-jobs/{id}`.
  3110. Source preference: ``source_3mf_path`` (the un-sliced project file the
  3111. user originally sent to slice) → ``file_path`` (the sliced 3MF/gcode that
  3112. actually printed).
  3113. """
  3114. from backend.app.api.routes.library import guard_nozzle_class_reslice, slice_and_persist_as_archive
  3115. from backend.app.core.database import async_session
  3116. from backend.app.services.slice_dispatch import (
  3117. http_exception_to_job_error,
  3118. slice_dispatch,
  3119. )
  3120. archive = await db.get(PrintArchive, archive_id)
  3121. if archive is None:
  3122. raise HTTPException(status_code=404, detail="Archive not found")
  3123. src_relative = archive.source_3mf_path or archive.file_path
  3124. if not src_relative:
  3125. raise HTTPException(
  3126. status_code=400,
  3127. detail="Archive has no source file to slice",
  3128. )
  3129. src_path = (
  3130. Path(settings.base_dir) / src_relative
  3131. ) # SEC-PATH-OK: src_relative is archive.source_3mf_path from DB, set by _resolve_source_3mf_path which already does resolve+relative_to containment
  3132. if not src_path.exists():
  3133. raise HTTPException(status_code=404, detail="Archive source file missing on disk")
  3134. raw_filename = archive.filename or src_path.name
  3135. src_lower = raw_filename.lower()
  3136. if not (
  3137. src_lower.endswith(".stl")
  3138. or src_lower.endswith(".3mf")
  3139. or src_lower.endswith(".step")
  3140. or src_lower.endswith(".stp")
  3141. ):
  3142. raise HTTPException(
  3143. status_code=400,
  3144. detail="Archive's source file must be STL, 3MF, or STEP to slice",
  3145. )
  3146. # Match the library route: derive the sliced output's filename from
  3147. # `print_name` when set, so the new archive row's display name lines
  3148. # up with the source's display.
  3149. src_ext = Path(raw_filename).suffix.lower() or ".3mf"
  3150. src_filename = (
  3151. f"{archive.print_name.strip()}{src_ext}" if archive.print_name and archive.print_name.strip() else raw_filename
  3152. )
  3153. model_bytes = src_path.read_bytes()
  3154. archive_id_local = archive.id
  3155. user_id = current_user.id if current_user else None
  3156. # Block a cross-nozzle-class re-slice (single-nozzle <-> H2D) up front —
  3157. # BambuStudio's multi-extruder validator would otherwise reject it with a
  3158. # cryptic error. No-op for same-class or un-sliced sources.
  3159. await guard_nozzle_class_reslice(db, current_user, request, archive.sliced_for_model)
  3160. async def _run(job_id: int):
  3161. async with async_session() as task_db:
  3162. # Re-fetch the source archive on the background-task session.
  3163. src_archive = await task_db.get(PrintArchive, archive_id_local)
  3164. if src_archive is None:
  3165. raise http_exception_to_job_error(
  3166. HTTPException(status_code=404, detail="Archive disappeared during slice")
  3167. )
  3168. try:
  3169. response = await slice_and_persist_as_archive(
  3170. task_db,
  3171. model_bytes=model_bytes,
  3172. model_filename=src_filename,
  3173. request=request,
  3174. source_archive=src_archive,
  3175. current_user_id=user_id,
  3176. job_id=job_id,
  3177. )
  3178. except HTTPException as exc:
  3179. raise http_exception_to_job_error(exc) from exc
  3180. return response.model_dump()
  3181. job = await slice_dispatch.enqueue(
  3182. kind="archive",
  3183. source_id=archive.id,
  3184. source_name=archive.print_name or archive.filename or f"archive {archive.id}",
  3185. run=_run,
  3186. )
  3187. return {
  3188. "job_id": job.id,
  3189. "status": job.status,
  3190. "status_url": f"/api/v1/slice-jobs/{job.id}",
  3191. }
  3192. @router.post("/{archive_id}/reprint")
  3193. async def reprint_archive(
  3194. archive_id: int,
  3195. printer_id: int,
  3196. body: ReprintRequest | None = None,
  3197. db: AsyncSession = Depends(get_db),
  3198. auth_result: tuple[User | None, bool] = Depends(
  3199. require_ownership_permission(
  3200. Permission.ARCHIVES_REPRINT_ALL,
  3201. Permission.ARCHIVES_REPRINT_OWN,
  3202. )
  3203. ),
  3204. ):
  3205. """Dispatch an archived 3MF file for send/start on a printer."""
  3206. from backend.app.models.printer import Printer
  3207. from backend.app.services.background_dispatch import DispatchEnqueueRejected, background_dispatch
  3208. from backend.app.services.printer_manager import printer_manager
  3209. user, can_modify_all = auth_result
  3210. # Use defaults if no body provided
  3211. if body is None:
  3212. body = ReprintRequest()
  3213. # Get archive
  3214. service = ArchiveService(db)
  3215. archive = await service.get_archive(archive_id)
  3216. if not archive:
  3217. raise HTTPException(404, "Archive not found")
  3218. # Ownership check
  3219. if not can_modify_all:
  3220. if archive.created_by_id != user.id:
  3221. raise HTTPException(403, "You can only reprint your own archives")
  3222. # Get printer
  3223. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3224. printer = result.scalar_one_or_none()
  3225. if not printer:
  3226. raise HTTPException(404, "Printer not found")
  3227. # Check printer is connected
  3228. if not printer_manager.is_connected(printer_id):
  3229. raise HTTPException(400, "Printer is not connected")
  3230. if not archive.file_path:
  3231. raise HTTPException(
  3232. 404,
  3233. "No 3MF file available for this archive. "
  3234. "The file could not be downloaded from the printer when the print was recorded.",
  3235. )
  3236. # Validate archive file exists
  3237. file_path = settings.base_dir / archive.file_path
  3238. if not file_path.is_file():
  3239. raise HTTPException(404, "Archive file not found")
  3240. plate_name = body.plate_name
  3241. if not plate_name and body.plate_id is not None:
  3242. plate_name = f"Plate {body.plate_id}"
  3243. dispatch_source_name = archive.filename
  3244. if plate_name:
  3245. dispatch_source_name = f"{archive.filename} • {plate_name}"
  3246. try:
  3247. dispatch_result = await background_dispatch.dispatch_reprint_archive(
  3248. archive_id=archive_id,
  3249. archive_name=dispatch_source_name,
  3250. printer_id=printer_id,
  3251. printer_name=printer.name,
  3252. options=body.model_dump(exclude_none=True),
  3253. requested_by_user_id=user.id if user else None,
  3254. requested_by_username=user.username if user else None,
  3255. )
  3256. except DispatchEnqueueRejected as e:
  3257. raise HTTPException(status_code=409, detail=str(e)) from e
  3258. logger.info(
  3259. "Dispatched reprint archive %s for printer %s (dispatch_job_id=%s, dispatch_position=%s)",
  3260. archive_id,
  3261. printer_id,
  3262. dispatch_result["dispatch_job_id"],
  3263. dispatch_result["dispatch_position"],
  3264. )
  3265. return {
  3266. "status": "dispatched",
  3267. "printer_id": printer_id,
  3268. "archive_id": archive_id,
  3269. "filename": archive.filename,
  3270. "dispatch_job_id": dispatch_result["dispatch_job_id"],
  3271. "dispatch_position": dispatch_result["dispatch_position"],
  3272. }
  3273. # =============================================================================
  3274. # Project Page API
  3275. # =============================================================================
  3276. @router.get("/{archive_id}/project-page")
  3277. async def get_project_page(
  3278. archive_id: int,
  3279. db: AsyncSession = Depends(get_db),
  3280. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3281. ):
  3282. """Get the project page data from the 3MF file."""
  3283. from backend.app.schemas.archive import ProjectPageResponse
  3284. from backend.app.services.archive import ProjectPageParser
  3285. service = ArchiveService(db)
  3286. archive = await service.get_archive(archive_id)
  3287. if not archive:
  3288. raise HTTPException(404, "Archive not found")
  3289. file_path = settings.base_dir / archive.file_path
  3290. if not file_path.is_file():
  3291. raise HTTPException(404, "Archive file not found")
  3292. parser = ProjectPageParser(file_path)
  3293. data = parser.parse(archive_id)
  3294. return ProjectPageResponse(**data)
  3295. @router.patch("/{archive_id}/project-page")
  3296. async def update_project_page(
  3297. archive_id: int,
  3298. update_data: dict,
  3299. db: AsyncSession = Depends(get_db),
  3300. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  3301. ):
  3302. """Update project page metadata in the 3MF file."""
  3303. from backend.app.services.archive import ProjectPageParser
  3304. service = ArchiveService(db)
  3305. archive = await service.get_archive(archive_id)
  3306. if not archive:
  3307. raise HTTPException(404, "Archive not found")
  3308. file_path = settings.base_dir / archive.file_path
  3309. if not file_path.is_file():
  3310. raise HTTPException(404, "Archive file not found")
  3311. parser = ProjectPageParser(file_path)
  3312. success = parser.update_metadata(update_data)
  3313. if not success:
  3314. raise HTTPException(500, "Failed to update project page")
  3315. # Return updated data
  3316. data = parser.parse(archive_id)
  3317. return data
  3318. @router.get("/{archive_id}/project-image/{image_path:path}")
  3319. async def get_project_image(
  3320. archive_id: int,
  3321. image_path: str,
  3322. db: AsyncSession = Depends(get_db),
  3323. _: None = RequireCameraStreamTokenIfAuthEnabled,
  3324. ):
  3325. """Get an image from the 3MF project page.
  3326. Requires a stream token query param (?token=xxx) when auth is enabled.
  3327. """
  3328. from backend.app.services.archive import ProjectPageParser
  3329. service = ArchiveService(db)
  3330. archive = await service.get_archive(archive_id)
  3331. if not archive:
  3332. raise HTTPException(404, "Archive not found")
  3333. file_path = settings.base_dir / archive.file_path
  3334. if not file_path.is_file():
  3335. raise HTTPException(404, "Archive file not found")
  3336. parser = ProjectPageParser(file_path)
  3337. result = parser.get_image(image_path)
  3338. if not result:
  3339. raise HTTPException(404, "Image not found in 3MF file")
  3340. image_data, content_type = result
  3341. return Response(
  3342. content=image_data,
  3343. media_type=content_type,
  3344. headers={"Cache-Control": "max-age=3600"},
  3345. )
  3346. # =============================================================================
  3347. # Source 3MF API (Original Project Files)
  3348. # =============================================================================
  3349. def _resolve_source_3mf_path(archive: PrintArchive, source_filename: str) -> Path:
  3350. """Resolve where to write a source 3MF for ``archive``.
  3351. Normal archives nest the source under ``<archive_file_dir>/source/``.
  3352. "Fallback" archives (created in main.py when MQTT reports a print start
  3353. but Bambuddy never saw the source 3MF — cloud / Handy / pre-existing
  3354. SD-card prints) carry ``file_path=""``. Joining that with ``base_dir``
  3355. via the ``/`` operator silently yields ``base_dir`` itself, whose parent
  3356. is ``base_dir.parent`` — which sent the upload to ``/app/source/`` and
  3357. raised a 500 on the final ``relative_to`` (#1531). Fallback archives
  3358. now land under ``<base_dir>/archive/no_source/<archive_id>/`` instead,
  3359. which stays inside the data volume and remains addressable by every
  3360. read site that does ``base_dir / archive.source_3mf_path``.
  3361. The resolved directory is asserted to be inside ``base_dir`` even when
  3362. ``archive.file_path`` is populated, so a row corrupted by an old import
  3363. or manual SQL edit fails with a clear 500 instead of writing outside
  3364. the data volume.
  3365. """
  3366. if archive.file_path:
  3367. archive_file = settings.base_dir / archive.file_path
  3368. source_dir = archive_file.parent / "source"
  3369. else:
  3370. source_dir = settings.base_dir / "archive" / "no_source" / str(archive.id)
  3371. # Containment check via resolve() — catches absolute file_path, `..`
  3372. # traversal, and any other shape that escapes the data volume — but we
  3373. # return the *literal* source_dir below. Resolving the returned path
  3374. # would canonicalise away a symlinked DATA_DIR (legitimate on TrueNAS /
  3375. # QNAP / Synology storage pools, and any `-v /symlink:/app/data`
  3376. # mount), which would then make the caller's
  3377. # ``source_path.relative_to(settings.base_dir)`` raise because the
  3378. # left side is canonical and the right is the symlink path.
  3379. try:
  3380. source_dir.resolve().relative_to(settings.base_dir.resolve())
  3381. except ValueError as exc:
  3382. raise HTTPException(
  3383. 500,
  3384. f"Archive {archive.id} resolves to a path outside the data directory; cannot attach source.",
  3385. ) from exc
  3386. source_dir.mkdir(parents=True, exist_ok=True)
  3387. return (
  3388. source_dir / source_filename
  3389. ) # SEC-PATH-OK: callers pass _safe_filename(...) basename-stripped; source_dir resolve+relative_to checked above
  3390. @router.post("/{archive_id}/source")
  3391. async def upload_source_3mf(
  3392. archive_id: int,
  3393. file: UploadFile = File(...),
  3394. db: AsyncSession = Depends(get_db),
  3395. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  3396. ):
  3397. """Upload the original source 3MF project file for an archive."""
  3398. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3399. archive = result.scalar_one_or_none()
  3400. if not archive:
  3401. raise HTTPException(404, "Archive not found")
  3402. if not file.filename or not file.filename.endswith(".3mf"):
  3403. raise HTTPException(400, "File must be a .3mf file")
  3404. # Save the source 3MF file - preserve original filename, strip directory components
  3405. source_filename = _safe_filename(file.filename)
  3406. source_path = _resolve_source_3mf_path(archive, source_filename)
  3407. # Delete old source file if exists
  3408. if archive.source_3mf_path:
  3409. old_source_path = settings.base_dir / archive.source_3mf_path
  3410. if old_source_path.exists():
  3411. old_source_path.unlink()
  3412. content = await file.read()
  3413. # #1401: validate zip header on source 3MF uploads too — source files
  3414. # are uploaded for reprint and slicing, so an invalid one breaks the
  3415. # same downstream paths as a bad sliced file.
  3416. from backend.app.api.routes.library import validate_print_file_upload
  3417. validate_print_file_upload(file.filename, content)
  3418. source_path.write_bytes(content)
  3419. # Update archive with source path (relative to base_dir)
  3420. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  3421. await db.commit()
  3422. await db.refresh(archive)
  3423. return {
  3424. "status": "uploaded",
  3425. "source_3mf_path": archive.source_3mf_path,
  3426. "filename": source_filename,
  3427. }
  3428. @router.get("/{archive_id}/source")
  3429. async def download_source_3mf(
  3430. archive_id: int,
  3431. db: AsyncSession = Depends(get_db),
  3432. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3433. ):
  3434. """Download the source 3MF project file."""
  3435. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3436. archive = result.scalar_one_or_none()
  3437. if not archive:
  3438. raise HTTPException(404, "Archive not found")
  3439. if not archive.source_3mf_path:
  3440. raise HTTPException(404, "No source 3MF attached to this archive")
  3441. source_path = settings.base_dir / archive.source_3mf_path
  3442. if not source_path.exists():
  3443. raise HTTPException(404, "Source 3MF file not found on disk")
  3444. # Use the actual filename from the path
  3445. filename = source_path.name
  3446. return FileResponse(
  3447. path=source_path,
  3448. filename=filename,
  3449. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3450. )
  3451. @router.get("/{archive_id}/source/{filename}")
  3452. async def download_source_3mf_for_slicer(
  3453. archive_id: int,
  3454. filename: str,
  3455. db: AsyncSession = Depends(get_db),
  3456. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3457. ):
  3458. """Download source 3MF with filename in URL."""
  3459. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3460. archive = result.scalar_one_or_none()
  3461. if not archive:
  3462. raise HTTPException(404, "Archive not found")
  3463. if not archive.source_3mf_path:
  3464. raise HTTPException(404, "No source 3MF attached to this archive")
  3465. source_path = settings.base_dir / archive.source_3mf_path
  3466. if not source_path.exists():
  3467. raise HTTPException(404, "Source 3MF file not found on disk")
  3468. return FileResponse(
  3469. path=source_path,
  3470. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  3471. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3472. )
  3473. @router.post("/{archive_id}/source-slicer-token")
  3474. async def create_source_slicer_token(
  3475. archive_id: int,
  3476. db: AsyncSession = Depends(get_db),
  3477. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3478. ):
  3479. """Create a short-lived download token for opening source 3MF in slicer."""
  3480. from backend.app.core.auth import create_slicer_download_token
  3481. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3482. archive = result.scalar_one_or_none()
  3483. if not archive:
  3484. raise HTTPException(404, "Archive not found")
  3485. if not archive.source_3mf_path:
  3486. raise HTTPException(404, "No source 3MF attached to this archive")
  3487. token = await create_slicer_download_token("source", archive_id)
  3488. return {"token": token}
  3489. @router.get("/{archive_id}/source-dl/{token}/{filename}")
  3490. async def download_source_3mf_for_slicer_with_token(
  3491. archive_id: int,
  3492. token: str,
  3493. filename: str,
  3494. db: AsyncSession = Depends(get_db),
  3495. ):
  3496. """Download source 3MF using a slicer download token.
  3497. Token-authenticated (no auth headers needed). The token is short-lived
  3498. and single-use, created by POST /{archive_id}/source-slicer-token.
  3499. """
  3500. from backend.app.core.auth import verify_slicer_download_token
  3501. if not await verify_slicer_download_token(token, "source", archive_id):
  3502. raise HTTPException(403, "Invalid or expired download token")
  3503. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3504. archive = result.scalar_one_or_none()
  3505. if not archive:
  3506. raise HTTPException(404, "Archive not found")
  3507. if not archive.source_3mf_path:
  3508. raise HTTPException(404, "No source 3MF attached to this archive")
  3509. source_path = settings.base_dir / archive.source_3mf_path
  3510. if not source_path.exists():
  3511. raise HTTPException(404, "Source 3MF file not found on disk")
  3512. return FileResponse(
  3513. path=source_path,
  3514. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  3515. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3516. )
  3517. @router.post("/upload-source")
  3518. async def upload_source_3mf_by_name(
  3519. file: UploadFile = File(...),
  3520. print_name: str = Query(None, description="Match archive by print name"),
  3521. db: AsyncSession = Depends(get_db),
  3522. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  3523. ):
  3524. """Upload source 3MF and match to archive by print name.
  3525. This endpoint is designed for slicer post-processing scripts.
  3526. It finds the most recent archive matching the print name and attaches the source.
  3527. """
  3528. if not file.filename or not file.filename.endswith(".3mf"):
  3529. raise HTTPException(400, "File must be a .3mf file")
  3530. safe_filename = _safe_filename(file.filename)
  3531. # Derive print name from filename if not provided
  3532. if not print_name:
  3533. # Remove .3mf extension and common suffixes
  3534. print_name = safe_filename.rsplit(".3mf", 1)[0]
  3535. # Remove _source suffix if present
  3536. if print_name.endswith("_source"):
  3537. print_name = print_name[:-7]
  3538. # Find matching archive - try exact match first, then fuzzy
  3539. result = await db.execute(
  3540. select(PrintArchive)
  3541. .where(PrintArchive.print_name == print_name)
  3542. .order_by(PrintArchive.created_at.desc())
  3543. .limit(1)
  3544. )
  3545. archive = result.scalar_one_or_none()
  3546. if not archive:
  3547. # Try matching filename without .gcode.3mf
  3548. result = await db.execute(
  3549. select(PrintArchive)
  3550. .where(PrintArchive.filename.like(f"{print_name}%"))
  3551. .order_by(PrintArchive.created_at.desc())
  3552. .limit(1)
  3553. )
  3554. archive = result.scalar_one_or_none()
  3555. if not archive:
  3556. # Try case-insensitive partial match on print_name
  3557. result = await db.execute(
  3558. select(PrintArchive)
  3559. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  3560. .order_by(PrintArchive.created_at.desc())
  3561. .limit(1)
  3562. )
  3563. archive = result.scalar_one_or_none()
  3564. if not archive:
  3565. raise HTTPException(404, f"No archive found matching '{print_name}'")
  3566. # Save the source 3MF file - preserve original filename, strip directory components
  3567. source_filename = safe_filename
  3568. source_path = _resolve_source_3mf_path(archive, source_filename)
  3569. # Delete old source file if exists
  3570. if archive.source_3mf_path:
  3571. old_source_path = settings.base_dir / archive.source_3mf_path
  3572. if old_source_path.exists():
  3573. old_source_path.unlink()
  3574. content = await file.read()
  3575. # #1401: same zip-header check as the other upload routes — the
  3576. # match-by-name endpoint is used by slicer post-processing scripts,
  3577. # so a misconfigured script is exactly how a bad 3MF would slip in.
  3578. from backend.app.api.routes.library import validate_print_file_upload
  3579. validate_print_file_upload(file.filename, content)
  3580. source_path.write_bytes(content)
  3581. # Update archive with source path
  3582. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  3583. await db.commit()
  3584. await db.refresh(archive)
  3585. return {
  3586. "status": "uploaded",
  3587. "archive_id": archive.id,
  3588. "archive_name": archive.print_name or archive.filename,
  3589. "source_3mf_path": archive.source_3mf_path,
  3590. "filename": source_filename,
  3591. }
  3592. @router.delete("/{archive_id}/source")
  3593. async def delete_source_3mf(
  3594. archive_id: int,
  3595. db: AsyncSession = Depends(get_db),
  3596. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  3597. ):
  3598. """Delete the source 3MF project file from an archive."""
  3599. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3600. archive = result.scalar_one_or_none()
  3601. if not archive:
  3602. raise HTTPException(404, "Archive not found")
  3603. if not archive.source_3mf_path:
  3604. raise HTTPException(404, "No source 3MF attached to this archive")
  3605. # Delete the file
  3606. source_path = settings.base_dir / archive.source_3mf_path
  3607. if source_path.exists():
  3608. source_path.unlink()
  3609. # Clear the path in database
  3610. archive.source_3mf_path = None
  3611. await db.commit()
  3612. return {"status": "deleted"}
  3613. # =============================================================================
  3614. # F3D API (Fusion 360 Design Files)
  3615. # =============================================================================
  3616. @router.post("/{archive_id}/f3d")
  3617. async def upload_f3d(
  3618. archive_id: int,
  3619. file: UploadFile = File(...),
  3620. db: AsyncSession = Depends(get_db),
  3621. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  3622. ):
  3623. """Upload a Fusion 360 design file for an archive."""
  3624. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3625. archive = result.scalar_one_or_none()
  3626. if not archive:
  3627. raise HTTPException(404, "Archive not found")
  3628. if not file.filename or not file.filename.endswith(".f3d"):
  3629. raise HTTPException(400, "File must be a .f3d file")
  3630. # Get archive directory and create f3d subdirectory
  3631. file_path = settings.base_dir / archive.file_path
  3632. archive_dir = file_path.parent
  3633. f3d_dir = archive_dir / "f3d"
  3634. f3d_dir.mkdir(exist_ok=True)
  3635. # Delete old F3D file if exists
  3636. if archive.f3d_path:
  3637. old_f3d_path = settings.base_dir / archive.f3d_path
  3638. if old_f3d_path.exists():
  3639. old_f3d_path.unlink()
  3640. # Save the F3D file - preserve original filename, strip directory components
  3641. f3d_filename = _safe_filename(file.filename)
  3642. f3d_path = f3d_dir / f3d_filename # SEC-PATH-OK: f3d_filename = _safe_filename(...) basename-stripped above
  3643. content = await file.read()
  3644. f3d_path.write_bytes(content)
  3645. # Update archive with F3D path (relative to base_dir)
  3646. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  3647. await db.commit()
  3648. await db.refresh(archive)
  3649. return {
  3650. "status": "uploaded",
  3651. "f3d_path": archive.f3d_path,
  3652. "filename": f3d_filename,
  3653. }
  3654. @router.get("/{archive_id}/f3d")
  3655. async def download_f3d(
  3656. archive_id: int,
  3657. db: AsyncSession = Depends(get_db),
  3658. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3659. ):
  3660. """Download the Fusion 360 design file."""
  3661. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3662. archive = result.scalar_one_or_none()
  3663. if not archive:
  3664. raise HTTPException(404, "Archive not found")
  3665. if not archive.f3d_path:
  3666. raise HTTPException(404, "No F3D file attached to this archive")
  3667. f3d_path = settings.base_dir / archive.f3d_path
  3668. if not f3d_path.exists():
  3669. raise HTTPException(404, "F3D file not found on disk")
  3670. # Use the actual filename from the path
  3671. filename = f3d_path.name
  3672. return FileResponse(
  3673. path=f3d_path,
  3674. filename=filename,
  3675. media_type="application/octet-stream",
  3676. )
  3677. @router.delete("/{archive_id}/f3d")
  3678. async def delete_f3d(
  3679. archive_id: int,
  3680. db: AsyncSession = Depends(get_db),
  3681. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  3682. ):
  3683. """Delete the Fusion 360 design file from an archive."""
  3684. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3685. archive = result.scalar_one_or_none()
  3686. if not archive:
  3687. raise HTTPException(404, "Archive not found")
  3688. if not archive.f3d_path:
  3689. raise HTTPException(404, "No F3D file attached to this archive")
  3690. # Delete the file
  3691. f3d_path = settings.base_dir / archive.f3d_path
  3692. if f3d_path.exists():
  3693. f3d_path.unlink()
  3694. # Clear the path in database
  3695. archive.f3d_path = None
  3696. await db.commit()
  3697. return {"status": "deleted"}