archives.py 139 KB

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