archives.py 153 KB

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