archives.py 135 KB

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