archives.py 164 KB

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