archives.py 152 KB

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