main.py 248 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214
  1. """
  2. 主应用入口
  3. """
  4. from __future__ import annotations
  5. import json
  6. import logging
  7. import io
  8. import urllib.parse
  9. import hashlib
  10. import uuid
  11. import math
  12. import random
  13. from decimal import Decimal
  14. import base64
  15. from datetime import datetime, timedelta
  16. from typing import Optional, List, Dict, Any, Literal
  17. from fastapi import FastAPI, WebSocket, HTTPException, Request, Query, Header, Depends, File, UploadFile, Form
  18. from fastapi.exceptions import RequestValidationError
  19. from fastapi.responses import RedirectResponse, PlainTextResponse, JSONResponse, StreamingResponse
  20. from fastapi.middleware.cors import CORSMiddleware
  21. from starlette.middleware.base import BaseHTTPMiddleware
  22. from starlette.requests import Request as StarletteRequest
  23. from starlette.responses import Response
  24. from pydantic import BaseModel, Field, field_validator, ValidationError as PydanticValidationError
  25. from contextlib import asynccontextmanager
  26. import httpx
  27. from xml.etree import ElementTree as ET
  28. from sqlalchemy import text, select, update
  29. from sqlalchemy.orm import selectinload
  30. from config import settings, get_dashscope_domain
  31. from websocket_handler import WebSocketHandler
  32. from database import init_database, close_database, db_manager
  33. from services.redis_cache_service import RedisCacheService
  34. from services.user_service import user_service, AuthError
  35. from ai_service import ai_service
  36. from error_codes import (
  37. UNAUTHORIZED_USER_MISMATCH,
  38. SESSION_NOT_INITIALIZED,
  39. SESSION_EXPIRED,
  40. USER_NOT_FOUND,
  41. USER_NOT_FOUND_REGISTER_FIRST,
  42. CREATE_USER_FAILED,
  43. INIT_SESSION_FAILED,
  44. GET_USER_INFO_FAILED,
  45. UPDATE_USERNAME_FAILED,
  46. USER_NOT_FOUND_OR_UPDATE_FAILED,
  47. UPDATE_BG_IMAGE_FAILED,
  48. UPDATE_BOT_NAME_FAILED,
  49. UPDATE_BOT_NAME_TIMEOUT,
  50. UPDATE_PREFERRED_LANGUAGE_FAILED,
  51. GET_ENERGY_STONES_FAILED,
  52. GET_AVATARS_FAILED,
  53. GET_BG_CONFIG_FAILED,
  54. GET_USER_BG_IMAGES_FAILED,
  55. CLAIM_SHARE_REWARD_FAILED,
  56. FEEDBACK_CONTENT_EMPTY,
  57. SUBMIT_FEEDBACK_FAILED,
  58. REGISTER_FAILED,
  59. LOGIN_FAILED,
  60. PHONE_REQUIRED,
  61. EMAIL_REQUIRED,
  62. SEND_TYPE_INVALID,
  63. SEND_CODE_FAILED,
  64. CODE_REQUIRED,
  65. VERIFY_CODE_FAILED,
  66. TYPE_MUST_BE_EMAIL_OR_PHONE,
  67. GET_UI_STATE_FAILED,
  68. UPDATE_UI_STATE_FAILED,
  69. WECHAT_OAUTH_NOT_CONFIGURED,
  70. QQ_OAUTH_NOT_CONFIGURED,
  71. WECHAT_MP_NOT_CONFIGURED,
  72. WECHAT_JSAPI_CONFIG_FAILED,
  73. GET_CONFIG_FAILED,
  74. SERVER_ERROR,
  75. INSUFFICIENT_CONVERSATION_ENERGY,
  76. PURCHASE_LIMIT_REACHED,
  77. SHOP_ITEM_NOT_FOUND,
  78. CART_QUANTITY_LIMIT_EXCEEDED,
  79. )
  80. from services.wechat_jsapi_service import WechatJSAPIService
  81. from services.energy_stone_service import energy_stone_service
  82. from services.scenario_topic_service import scenario_topic_service
  83. from services.llm_task_service import llm_task_service
  84. from services.ab_subtitle_service import ab_subtitle_service
  85. from services.chat_export_service import export_chat_records_zip, parse_identifiers_from_txt
  86. from scenario_config import is_special_ab_experiment_user
  87. from models_db import VerificationCode, UserAvatar, UserBackgroundImage, Feedback, BackgroundImage, User
  88. from session_store import SessionStore
  89. from shop_item_image_utils import scene_image_name_from_shop_row
  90. # 配置日志
  91. logging.basicConfig(
  92. level=getattr(logging, settings.LOG_LEVEL.upper(), logging.INFO),
  93. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  94. datefmt='%Y-%m-%d %H:%M:%S'
  95. )
  96. # 🔇 过滤第三方库的 DEBUG 日志(避免刷屏)
  97. # 这些库的 DEBUG 日志包含 HTTP/2 协议细节、HPACK 压缩等底层信息,对生产环境无意义
  98. third_party_loggers = [
  99. 'openai',
  100. 'openai._base_client',
  101. 'httpcore',
  102. 'httpcore.http2',
  103. 'httpx',
  104. 'hpack',
  105. 'hpack.hpack',
  106. 'hpack.table',
  107. ]
  108. for logger_name in third_party_loggers:
  109. logging.getLogger(logger_name).setLevel(logging.INFO)
  110. logger = logging.getLogger(__name__)
  111. @asynccontextmanager
  112. async def lifespan(app: FastAPI):
  113. """应用生命周期管理"""
  114. # 启动时初始化数据库(包含MySQL和Redis,自动启动健康检查任务)
  115. try:
  116. await init_database()
  117. # 获取Redis客户端(已配置健康检查),用于验证连通性
  118. from database import db_manager
  119. await db_manager.get_redis()
  120. # 创建Redis缓存服务,按需获取最新连接
  121. app.state.redis_cache = RedisCacheService(db_manager.get_redis)
  122. except Exception as e:
  123. logger.error(f"❌ 数据库初始化失败: {e}")
  124. app.state.redis_cache = None
  125. # 🔥 启动HTTP连接保活任务(保持连接活跃,避免长时间不交互后响应变慢)
  126. try:
  127. from http_pool import http_pool
  128. from ai_service import AIService
  129. # 创建AIService实例用于保活(共享连接池)
  130. ai_service = AIService()
  131. http_pool.start_keepalive(ai_service=ai_service)
  132. except Exception as e:
  133. logger.warning(f"⚠️ HTTP连接保活任务启动失败: {e}")
  134. yield
  135. # 关闭时清理资源
  136. await close_database()
  137. # 🔥 关闭HTTP连接池(类似SQLAlchemy的Engine.dispose())
  138. from http_pool import http_pool
  139. http_pool.close()
  140. app = FastAPI(
  141. title="Lyrria Backend API",
  142. lifespan=lifespan
  143. )
  144. # 全局会话存储(单用户单活 token),使用 Redis 持久化
  145. from database import db_manager # 延迟导入以避免循环依赖问题
  146. app.state.session_store = SessionStore(
  147. redis_getter=db_manager.get_redis,
  148. default_ttl_seconds=settings.SESSION_TOKEN_TTL_SECONDS,
  149. )
  150. class APIKeyMiddleware(BaseHTTPMiddleware):
  151. """API Key验证中间件"""
  152. # 不需要验证的路径(健康检查、WebSocket、微信/QQ回调等)
  153. EXEMPT_PATHS = [
  154. "/",
  155. "/docs",
  156. "/openapi.json",
  157. "/redoc",
  158. "/ws",
  159. # 微信 OAuth & 公众号回调
  160. "/api/auth/wechat/authorize",
  161. "/api/auth/wechat/callback",
  162. "/api/wechat/mp/verify",
  163. "/api/wechat/mp/message",
  164. # QQ OAuth & 回调
  165. "/api/auth/qq/authorize",
  166. "/api/qq/mp/verify",
  167. # QQ 分享配置(SDK 拉取)
  168. "/api/qq/share/config",
  169. # web-admin 免登录管理接口(按需求)
  170. "/api/admin",
  171. ]
  172. async def dispatch(self, request: StarletteRequest, call_next):
  173. # 检查是否为豁免路径
  174. path = request.url.path
  175. if any(path.startswith(exempt) for exempt in self.EXEMPT_PATHS):
  176. return await call_next(request)
  177. # 如果未启用API Key验证,直接通过
  178. if not settings.API_KEY_ENABLED:
  179. return await call_next(request)
  180. # 检查API Key
  181. api_key = request.headers.get("X-Client-Key", "")
  182. expected_key = settings.API_CLIENT_KEY
  183. if not expected_key:
  184. logger.warning("⚠️ API_CLIENT_KEY未配置,跳过验证")
  185. return await call_next(request)
  186. if api_key != expected_key:
  187. logger.warning(f"❌ API Key验证失败: path={path}, provided_key={'***' if api_key else '(empty)'}")
  188. return Response(
  189. content='{"detail":"Invalid API Key"}',
  190. status_code=403,
  191. media_type="application/json"
  192. )
  193. return await call_next(request)
  194. # 配置CORS - 使用配置中的允许来源
  195. cors_origins = settings.CORS_ORIGINS if not settings.CORS_ALLOW_ALL else ["*"]
  196. app.add_middleware(
  197. CORSMiddleware,
  198. allow_origins=cors_origins,
  199. allow_credentials=True,
  200. allow_methods=["*"],
  201. allow_headers=["*"],
  202. expose_headers=["X-Export-Count", "X-Not-Found-Count"],
  203. )
  204. # 添加API Key验证中间件(在CORS之后)
  205. app.add_middleware(APIKeyMiddleware)
  206. @app.exception_handler(RequestValidationError)
  207. async def validation_exception_handler(_request: Request, exc: RequestValidationError) -> JSONResponse:
  208. """422 时在服务端打印校验错误,便于排查(如 user_events 缺失字段)"""
  209. errors = exc.errors()
  210. for err in errors:
  211. logger.warning("422 校验失败: loc=%s msg=%s type=%s", err.get("loc"), err.get("msg"), err.get("type"))
  212. return JSONResponse(status_code=422, content={"detail": errors})
  213. async def require_user_session_from_headers(
  214. request: Request,
  215. header_user_id: Optional[str] = Header(None, alias="X-User-Id"),
  216. token: Optional[str] = Header(None, alias="X-User-Token"),
  217. ) -> str:
  218. """仅根据 X-User-Id + X-User-Token 校验会话,返回 user_id(用于无 path user_id 的接口如 POST /api/user-events)"""
  219. if not header_user_id or not token:
  220. logger.warning(
  221. "require_user_session_from_headers: missing headers - path=%s",
  222. request.url.path,
  223. )
  224. raise HTTPException(status_code=401, detail={"code": SESSION_EXPIRED})
  225. session_store = getattr(request.app.state, "session_store", None)
  226. if not session_store:
  227. logger.error(
  228. "require_user_session_from_headers: SESSION_NOT_INITIALIZED - path=%s",
  229. request.url.path,
  230. )
  231. raise HTTPException(status_code=500, detail={"code": SESSION_NOT_INITIALIZED})
  232. is_valid = await session_store.validate(header_user_id, token, refresh=True)
  233. if not is_valid:
  234. logger.warning(
  235. "require_user_session_from_headers: SESSION_EXPIRED - path=%s, user_id=%s",
  236. request.url.path,
  237. header_user_id,
  238. )
  239. raise HTTPException(status_code=401, detail={"code": SESSION_EXPIRED})
  240. return header_user_id
  241. async def require_user_session(
  242. request: Request,
  243. user_id: str,
  244. header_user_id: Optional[str] = Header(None, alias="X-User-Id"),
  245. token: Optional[str] = Header(None, alias="X-User-Token"),
  246. ) -> None:
  247. """
  248. 基于 user_id + token 的简单 HTTP 鉴权,复用 WebSocket 的 session_store。
  249. 仅用于需要用户身份的业务接口,保持单用户单活语义。
  250. """
  251. if not header_user_id or header_user_id != user_id:
  252. logger.warning(
  253. "require_user_session: UNAUTHORIZED_USER_MISMATCH - path=%s, param_user_id=%s, header_user_id=%s",
  254. request.url.path,
  255. user_id,
  256. header_user_id,
  257. )
  258. raise HTTPException(status_code=401, detail={"code": UNAUTHORIZED_USER_MISMATCH})
  259. session_store = getattr(request.app.state, "session_store", None)
  260. if not session_store:
  261. logger.error(
  262. "require_user_session: SESSION_NOT_INITIALIZED - path=%s, user_id=%s",
  263. request.url.path,
  264. header_user_id,
  265. )
  266. raise HTTPException(status_code=500, detail={"code": SESSION_NOT_INITIALIZED})
  267. if not token:
  268. logger.warning(
  269. "require_user_session: missing X-User-Token header - path=%s, user_id=%s",
  270. request.url.path,
  271. header_user_id,
  272. )
  273. raise HTTPException(status_code=401, detail={"code": SESSION_EXPIRED})
  274. is_valid = await session_store.validate(user_id, token, refresh=True)
  275. if not is_valid:
  276. try:
  277. entry = await session_store.get_current_token(user_id)
  278. except Exception as diag_exc: # noqa: BLE001
  279. logger.warning(
  280. "require_user_session: validate failed and get_current_token raised - path=%s, user_id=%s, token_prefix=%s, error=%r",
  281. request.url.path,
  282. user_id,
  283. str(token)[:8],
  284. diag_exc,
  285. )
  286. raise HTTPException(status_code=401, detail={"code": SESSION_EXPIRED})
  287. if entry is None:
  288. logger.warning(
  289. "require_user_session: SESSION_EXPIRED - no active session entry - path=%s, user_id=%s, token_prefix=%s",
  290. request.url.path,
  291. user_id,
  292. str(token)[:8],
  293. )
  294. else:
  295. try:
  296. expires_iso = datetime.fromtimestamp(entry.expires_at).isoformat()
  297. except Exception:
  298. expires_iso = str(entry.expires_at)
  299. logger.warning(
  300. "require_user_session: SESSION_EXPIRED - token mismatch or expired - path=%s, user_id=%s, header_token_prefix=%s, stored_token_prefix=%s, stored_expires_at=%s, now=%s",
  301. request.url.path,
  302. user_id,
  303. str(token)[:8],
  304. str(entry.token)[:8],
  305. expires_iso,
  306. datetime.utcnow().isoformat(),
  307. )
  308. raise HTTPException(status_code=401, detail={"code": SESSION_EXPIRED})
  309. async def optional_user_id(
  310. request: Request,
  311. header_user_id: Optional[str] = Header(None, alias="X-User-Id"),
  312. token: Optional[str] = Header(None, alias="X-User-Token"),
  313. ) -> Optional[str]:
  314. """可选鉴权:有且有效则返回 user_id,否则返回 None(用于页面访问等不强制登录的接口)"""
  315. if not header_user_id or not token:
  316. return None
  317. session_store = getattr(request.app.state, "session_store", None)
  318. if not session_store or not await session_store.validate(header_user_id, token, refresh=False):
  319. return None
  320. return header_user_id
  321. class AdminCreateEnergyGiftInboxRequest(BaseModel):
  322. title_zh: str = Field(..., min_length=1, max_length=200)
  323. title_en: str = Field(..., min_length=1, max_length=200)
  324. content_zh: str = Field(..., min_length=1, max_length=10000)
  325. content_en: str = Field(..., min_length=1, max_length=10000)
  326. energy_stone_amount: int = Field(..., gt=0, le=100000)
  327. user_ids: List[str] = Field(..., min_length=1)
  328. @field_validator("user_ids")
  329. @classmethod
  330. def validate_user_ids(cls, value: List[str]) -> List[str]:
  331. normalized = [str(v).strip() for v in value if str(v).strip()]
  332. if not normalized:
  333. raise ValueError("user_ids不能为空")
  334. return list(dict.fromkeys(normalized))
  335. class AdminCreateNewsInboxRequest(BaseModel):
  336. title_zh: str = Field(..., min_length=1, max_length=200)
  337. title_en: str = Field(..., min_length=1, max_length=200)
  338. content_zh: str = Field(..., min_length=1, max_length=10000)
  339. content_en: str = Field(..., min_length=1, max_length=10000)
  340. ADMIN_INBOX_MESSAGE_TYPES = frozenset({"energy_gift", "news_notice", "ab_notice"})
  341. DELETABLE_INBOX_MESSAGE_TYPES = frozenset({"news_notice", "ab_notice"})
  342. class AdminCreateLlmTaskRequest(BaseModel):
  343. task_name: str = Field(..., min_length=1, max_length=255)
  344. task_prompt: str = Field(..., min_length=1, max_length=65535)
  345. lumi_first_line: str = Field(..., min_length=1, max_length=2000)
  346. class AdminUpdateLlmTaskRequest(AdminCreateLlmTaskRequest):
  347. pass
  348. class AdminUpdateAbSubtitleSettingRequest(BaseModel):
  349. subtitle_on: int = Field(..., ge=0, le=1, description="字幕开关:0=关,1=开")
  350. @app.get("/")
  351. async def root():
  352. """健康检查"""
  353. return {"status": "ok", "message": "Lyrria Backend API"}
  354. @app.post("/api/user-events")
  355. async def create_user_event(
  356. http_request: Request,
  357. auth_user_id: str = Depends(require_user_session_from_headers),
  358. ) -> Dict[str, Any]:
  359. """
  360. 前端上报单条用户事件
  361. - 主要用于页面进入、按钮点击等埋点
  362. - event_name 必须遵循 .cursorrules 中的“埋点事件命名规范”
  363. - 从 body 手动读取并校验,避免与依赖中的 Request 冲突导致 body 被当成 query
  364. """
  365. try:
  366. body = await http_request.json()
  367. except Exception as e:
  368. logger.warning("user_events 读取 body 失败: %s", e)
  369. raise HTTPException(status_code=422, detail=[{"type": "value_error", "loc": ("body",), "msg": "Invalid JSON body"}])
  370. try:
  371. payload = UserEventPayload.model_validate(body)
  372. except PydanticValidationError as val_err:
  373. logger.warning("user_events 校验失败: %s", val_err.errors())
  374. raise RequestValidationError(val_err.errors()) from val_err
  375. if payload.user_id != auth_user_id:
  376. raise HTTPException(status_code=401, detail={"code": UNAUTHORIZED_USER_MISMATCH})
  377. try:
  378. ok = await user_service.save_user_event(payload.model_dump())
  379. if not ok:
  380. logger.warning("user_events 落库返回 False: event_id=%s, event_name=%s", payload.event_id, payload.event_name)
  381. raise HTTPException(status_code=500, detail="failed_to_save_user_event")
  382. logger.info("user_events 已写入: event_name=%s, user_id=%s", payload.event_name, payload.user_id)
  383. return {"success": True}
  384. except HTTPException:
  385. raise
  386. except Exception as e: # noqa: BLE001
  387. logger.error(f"❌ 保存用户事件失败: event_id={payload.event_id}, error={e}")
  388. raise HTTPException(status_code=500, detail="failed_to_save_user_event") from e
  389. class CreateUserRequest(BaseModel):
  390. """创建用户请求"""
  391. username: str = Field("", description="用户名/昵称,可为空字符串")
  392. bot_name: Optional[str] = Field(None, description="机器人名字,可选")
  393. user_segment: str = Field("individual", description="用户分群:individual/school/internal等")
  394. org_id: Optional[str] = Field(None, description="组织ID(学校/机构用户)")
  395. is_test_user: bool = Field(False, description="是否测试账号")
  396. region: Optional[str] = Field(None, description="国家/地区代码,如 CN/US")
  397. class UpdateUsernameRequest(BaseModel):
  398. """更新用户名请求"""
  399. username: str
  400. class UpdateBotNameRequest(BaseModel):
  401. """更新机器人名字请求"""
  402. bot_name: str
  403. class UpdatePreferredLanguageRequest(BaseModel):
  404. """更新用户界面语言偏好(zh/en)"""
  405. preferred_language: Literal["zh", "en"]
  406. class UpdateBackgroundImageIdRequest(BaseModel):
  407. """更新背景图片ID请求"""
  408. background_image_id: str
  409. class UpdateChatbotBackdropRequest(BaseModel):
  410. """切换 ChatBot 幕布请求"""
  411. backdrop_item_id: int
  412. class ChatbotFurnitureActionRequest(BaseModel):
  413. """装备/卸下 ChatBot 家具请求"""
  414. item_id: int
  415. class ChatbotShopPurchaseRequest(BaseModel):
  416. """ChatBot 商店购买家具/幕布"""
  417. item_id: int
  418. class ChatbotShopCartAddRequest(BaseModel):
  419. """ChatBot 商店加入购物车(家具/幕布)"""
  420. item_id: int
  421. class ChatbotShopCartRemoveRequest(BaseModel):
  422. """ChatBot 商店移除购物车商品(家具/幕布)"""
  423. item_id: int
  424. class ChatbotShopCartPurchaseRequest(BaseModel):
  425. """ChatBot 商店购买购物车全部商品(家具/幕布)"""
  426. pass
  427. def _floor_shop_price_energy(price: object) -> int:
  428. """与 energy_stone_service 一致:售价向下取整为整颗对话能量石。"""
  429. try:
  430. v = float(price or 0)
  431. except (TypeError, ValueError):
  432. return 0
  433. if v <= 0:
  434. return 0
  435. return int(math.floor(v))
  436. class UserEventPayload(BaseModel):
  437. """前端上报用户事件 payload(单条)"""
  438. event_id: str = Field(..., description="事件ID,客户端或服务端生成,需全局唯一")
  439. user_id: str = Field(..., description="用户ID(关联 users.user_id)")
  440. event_name: str = Field(..., description="事件代码,如 page.chatbot__enter(遵循埋点命名规范)")
  441. event_label: Optional[str] = Field(None, description="事件中文名称/描述")
  442. event_time: datetime = Field(..., description="事件发生时间(UTC)")
  443. session_id: Optional[str] = Field(None, description="会话ID,同一次前台停留共享")
  444. platform: str = Field(..., description="平台:ios/android/web")
  445. app_version: Optional[str] = Field(None, description="应用版本号,如 v0.1.x")
  446. timezone_offset_minutes: Optional[int] = Field(
  447. None,
  448. description="用户本地相对UTC的分钟偏移量(分钟)",
  449. )
  450. properties: Optional[Dict[str, Any]] = Field(
  451. None,
  452. description="扩展属性(page、entry、button_id、duration_seconds 等)",
  453. )
  454. @field_validator("event_time", mode="before")
  455. @classmethod
  456. def parse_event_time(cls, v: Any) -> datetime:
  457. """接受 ISO 字符串(含 Z 后缀),避免 422"""
  458. if isinstance(v, datetime):
  459. return v
  460. if isinstance(v, str):
  461. s = v.strip().replace("Z", "+00:00")
  462. return datetime.fromisoformat(s)
  463. raise ValueError("event_time 需为 datetime 或 ISO 字符串")
  464. class RegisterPhoneRequest(BaseModel):
  465. """手机号注册请求"""
  466. area_code: Optional[str] = None
  467. phone: str
  468. username: str = ""
  469. user_id: Optional[str] = None # 可选的现有用户ID,如果提供则更新该用户而不是创建新用户
  470. preferred_language: Optional[str] = None # "zh" | "en"
  471. class RegisterEmailRequest(BaseModel):
  472. """邮箱注册请求"""
  473. email: str
  474. username: str = ""
  475. user_id: Optional[str] = None # 可选的现有用户ID,如果提供则更新该用户而不是创建新用户
  476. preferred_language: Optional[str] = None # "zh" | "en"
  477. class LoginWechatRequest(BaseModel):
  478. """微信登录请求"""
  479. openid: str
  480. username: str = ""
  481. class LoginQQRequest(BaseModel):
  482. """QQ登录请求"""
  483. openid: str
  484. username: str = ""
  485. class LoginPhoneRequest(BaseModel):
  486. """手机号登录请求"""
  487. area_code: Optional[str] = None
  488. phone: str
  489. preferred_language: Optional[str] = None # "zh" | "en"
  490. class LoginEmailRequest(BaseModel):
  491. """邮箱登录请求"""
  492. email: str
  493. preferred_language: Optional[str] = None # "zh" | "en"
  494. class EmailContinueRequest(BaseModel):
  495. """邮箱 Continue:特殊 A/B 用户免验证码登录,其余用户发验证码"""
  496. email: str
  497. preferred_language: Optional[str] = None # "zh" | "en"
  498. opted_out: Optional[bool] = None # 是否退出早期共创社区
  499. class SendCodeRequest(BaseModel):
  500. """发送验证码请求"""
  501. area_code: Optional[str] = None # 手机区号(如 +86)
  502. phone: Optional[str] = None
  503. email: Optional[str] = None
  504. send_type: str # "domestic_sms", "international_sms", "email"
  505. class VerifyCodeRequest(BaseModel):
  506. """验证验证码请求"""
  507. phone: Optional[str] = None
  508. email: Optional[str] = None
  509. code: str
  510. send_type: str # "domestic_sms", "international_sms", "email"
  511. class VerifyAndAuthRequest(BaseModel):
  512. """V2.0 验证码通过后统一登录/注册请求"""
  513. type: str # "email" | "phone"
  514. code: str
  515. email: Optional[str] = None
  516. phone: Optional[str] = None
  517. area_code: Optional[str] = None
  518. preferred_language: Optional[str] = None # "zh" | "en"
  519. class CommunityChoiceRequest(BaseModel):
  520. """V2.0 退出早期共创社区选项"""
  521. opted_out: bool
  522. class EarlyCommunityRequest(BaseModel):
  523. """V2.0 早期共创邮箱(可选)"""
  524. email: Optional[str] = None
  525. class UserUIStateResponse(BaseModel):
  526. """用户前端可视化状态"""
  527. user_id: str
  528. current_page: Optional[str] = None
  529. visited_routes: List[str] = []
  530. has_shown_tap_to_chat: bool = False
  531. has_shown_cancel_tooltip: bool = False
  532. has_shown_send_tooltip: bool = False
  533. has_shown_progress_bar_tooltip: bool = False
  534. has_shown_mission_stone_modal: bool = False
  535. has_shown_conversation_stone_modal: bool = False
  536. has_clicked_mission_stone: bool = False
  537. has_clicked_conversation_stone: bool = False
  538. subtitle_on: bool = False
  539. avatar_c_unlocked: bool = False
  540. has_shared_avatar: bool = False
  541. current_avatar_id: Optional[str] = None
  542. sfx_enabled: bool = True
  543. bgm_enabled: bool = True
  544. class PageVisitRequest(BaseModel):
  545. """页面访问上报"""
  546. path: str
  547. class UpdateUserUIStateRequest(BaseModel):
  548. """部分更新用户前端可视化状态"""
  549. current_page: Optional[str] = None
  550. visited_routes: Optional[List[str]] = None
  551. has_shown_tap_to_chat: Optional[bool] = None
  552. has_shown_cancel_tooltip: Optional[bool] = None
  553. has_shown_send_tooltip: Optional[bool] = None
  554. has_shown_progress_bar_tooltip: Optional[bool] = None
  555. has_shown_mission_stone_modal: Optional[bool] = None
  556. has_shown_conversation_stone_modal: Optional[bool] = None
  557. has_clicked_mission_stone: Optional[bool] = None
  558. has_clicked_conversation_stone: Optional[bool] = None
  559. has_shown_first_shop_tooltip: Optional[bool] = None
  560. has_clicked_shop_in_settings: Optional[bool] = None
  561. avatar_c_unlocked: Optional[bool] = None
  562. has_shared_avatar: Optional[bool] = None
  563. current_avatar_id: Optional[str] = None
  564. subtitle_on: Optional[bool] = None
  565. sfx_enabled: Optional[bool] = None
  566. bgm_enabled: Optional[bool] = None
  567. # 分享图片响应模型
  568. class ShareImageItem(BaseModel):
  569. id: str
  570. url: str
  571. title: Optional[str] = None
  572. sort_order: Optional[int] = None
  573. is_active: Optional[bool] = None
  574. SHARE_IMAGES: List[ShareImageItem] = [
  575. ShareImageItem(id="share-1", url="https://www.lyrria.com/img/share-1.png"),
  576. ShareImageItem(id="share-2", url="https://www.lyrria.com/img/share-2.png"),
  577. ]
  578. class AvatarGifSet(BaseModel):
  579. default: str
  580. positive: str
  581. negative: str
  582. talking: str
  583. async def _generate_session_token(user_id: str) -> Dict[str, Any]:
  584. """
  585. 为指定用户生成会话 token(复用 init_session 的逻辑)
  586. Args:
  587. user_id: 用户ID
  588. Returns:
  589. 包含 token 和 expires_at 的字典
  590. """
  591. session_store = getattr(app.state, "session_store", None)
  592. token = str(uuid.uuid4())
  593. expires_at = datetime.utcnow() + timedelta(seconds=settings.SESSION_TOKEN_TTL_SECONDS)
  594. if session_store:
  595. await session_store.set_current_token(user_id, token, settings.SESSION_TOKEN_TTL_SECONDS)
  596. # 主动踢掉旧连接
  597. await session_store.invalidate_connection(user_id)
  598. return {
  599. "token": token,
  600. "expires_at": expires_at.isoformat() + "Z",
  601. }
  602. class SessionInitRequest(BaseModel):
  603. user_id: Optional[str] = None
  604. username: Optional[str] = ""
  605. AVATAR_GIF_CONFIG = {
  606. "avatar_default": AvatarGifSet(
  607. default="https://www.lyrria.com/img/01-Default.gif",
  608. positive="https://www.lyrria.com/img/04-Positive-emotion.gif",
  609. negative="https://www.lyrria.com/img/05-Negative-emotion.gif",
  610. talking="https://www.lyrria.com/img/06-talking.gif",
  611. ),
  612. "avatar_registered_cap": AvatarGifSet(
  613. default="https://www.lyrria.com/img/01-Default-Registered.gif",
  614. positive="https://www.lyrria.com/img/04-Positive-emotion-Registered.gif",
  615. negative="https://www.lyrria.com/img/05-Negative-emotion-Registered.gif",
  616. talking="https://www.lyrria.com/img/06-talking-Registered.gif",
  617. ),
  618. }
  619. @app.post("/api/users/create")
  620. async def create_user(request: CreateUserRequest):
  621. """
  622. 创建游客用户
  623. Returns:
  624. {
  625. "user_id": "uuid",
  626. "username": "",
  627. "user_type": "guest",
  628. "bot_name": "机器人名字(可选)"
  629. }
  630. """
  631. try:
  632. user = await user_service.create_guest_user(
  633. username=request.username,
  634. bot_name=request.bot_name,
  635. user_segment=request.user_segment,
  636. org_id=request.org_id,
  637. is_test_user=request.is_test_user,
  638. region=request.region,
  639. )
  640. return {
  641. "success": True,
  642. "data": user
  643. }
  644. except Exception as e:
  645. logger.exception("创建用户失败")
  646. raise HTTPException(status_code=500, detail={"code": CREATE_USER_FAILED})
  647. @app.post("/api/session/init")
  648. async def init_session(request: SessionInitRequest):
  649. """
  650. 初始化或刷新用户会话,返回 user_id + 会话 token(单用户单活)
  651. """
  652. try:
  653. session_store = getattr(app.state, "session_store", None)
  654. # 1. 获取或创建用户
  655. user_id = request.user_id
  656. user_payload: Optional[Dict[str, Any]] = None
  657. if not user_id:
  658. user_payload = await user_service.create_guest_user(
  659. username=request.username or ""
  660. )
  661. user_id = user_payload["user_id"]
  662. else:
  663. # 确认用户存在
  664. user_payload = await user_service.get_user(user_id)
  665. if not user_payload:
  666. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  667. # 2. 签发新 token(覆盖旧 token,单活)
  668. token = str(uuid.uuid4())
  669. expires_at = datetime.utcnow() + timedelta(seconds=settings.SESSION_TOKEN_TTL_SECONDS)
  670. if session_store:
  671. await session_store.set_current_token(user_id, token, settings.SESSION_TOKEN_TTL_SECONDS)
  672. # 主动踢掉旧连接
  673. await session_store.invalidate_connection(user_id)
  674. data = {
  675. "user_id": user_id,
  676. "token": token,
  677. "expires_at": expires_at.isoformat() + "Z",
  678. }
  679. # 如果刚创建用户,透传部分信息,兼容前端缓存逻辑
  680. if user_payload:
  681. data.update(
  682. {
  683. "username": user_payload.get("username"),
  684. "user_level": user_payload.get("user_level"),
  685. "current_background_image_id": user_payload.get(
  686. "current_background_image_id"
  687. ),
  688. "current_background_image_metadata": user_payload.get(
  689. "current_background_image_metadata"
  690. ),
  691. }
  692. )
  693. return {"success": True, "data": data}
  694. except HTTPException:
  695. raise
  696. except Exception as e:
  697. logger.exception("初始化会话失败")
  698. raise HTTPException(status_code=500, detail={"code": INIT_SESSION_FAILED})
  699. @app.get("/api/users/{user_id}")
  700. async def get_user(user_id: str, _: None = Depends(require_user_session)):
  701. """
  702. 获取用户信息
  703. Args:
  704. user_id: 用户ID
  705. Returns:
  706. {
  707. "success": true,
  708. "data": {
  709. "user_id": "uuid",
  710. "username": "",
  711. "user_type": "guest",
  712. "bot_name": "机器人名字(可选)",
  713. ...
  714. }
  715. }
  716. """
  717. try:
  718. user = await user_service.get_user(user_id)
  719. if user:
  720. return {
  721. "success": True,
  722. "data": user
  723. }
  724. else:
  725. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  726. except HTTPException:
  727. raise
  728. except Exception as e:
  729. logger.exception("获取用户信息失败")
  730. raise HTTPException(status_code=500, detail={"code": GET_USER_INFO_FAILED})
  731. @app.get("/api/users/{user_id}/energy-stones/count")
  732. async def get_energy_stone_counts(user_id: str, _: None = Depends(require_user_session)):
  733. """
  734. 获取用户的能量石数量
  735. Args:
  736. user_id: 用户ID
  737. Returns:
  738. {
  739. "success": true,
  740. "data": {
  741. "mission_count": 0,
  742. "conversation_count": 0
  743. }
  744. }
  745. """
  746. try:
  747. if not energy_stone_service.db:
  748. await energy_stone_service.set_db_manager(db_manager)
  749. counts = await energy_stone_service.get_stone_counts(user_id)
  750. return {
  751. "success": True,
  752. "data": counts
  753. }
  754. except Exception as e:
  755. logger.exception("获取能量石数量失败")
  756. raise HTTPException(status_code=500, detail={"code": GET_ENERGY_STONES_FAILED})
  757. @app.get("/api/users/{user_id}/journal-latest-topic")
  758. async def get_journal_latest_topic(user_id: str, _: None = Depends(require_user_session)):
  759. """
  760. 个人页「日记本」左侧图:用户最近在 ChatBot 触发特殊情景话题的最新一条记录。
  761. 无记录时 data 为 null。
  762. """
  763. try:
  764. if not scenario_topic_service.db:
  765. await scenario_topic_service.set_db_manager(db_manager)
  766. latest = await scenario_topic_service.get_latest_log_for_journal(user_id)
  767. return {"success": True, "data": latest}
  768. except Exception:
  769. logger.exception("获取日记本最近情景话题失败")
  770. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  771. @app.get("/api/config/ab-subtitle")
  772. async def get_ab_subtitle_config():
  773. """A/B 组字幕开关配置(A=0 关,B=1 开),供前端读取实验策略。"""
  774. try:
  775. settings_map = await ab_subtitle_service.get_all_settings_cached()
  776. return {"success": True, "data": settings_map}
  777. except Exception:
  778. logger.exception("获取 A/B 字幕配置失败")
  779. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  780. @app.get("/api/users/{user_id}/ab-llm-task")
  781. async def get_ab_llm_task(user_id: str, _: None = Depends(require_user_session)):
  782. """A/B 组实验用户:返回当前最新 LLM 任务名称(不含 prompt)。"""
  783. try:
  784. user = await user_service.get_user(user_id)
  785. if not user:
  786. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  787. if not is_special_ab_experiment_user(user):
  788. raise HTTPException(status_code=403, detail={"code": "FORBIDDEN"})
  789. task = await llm_task_service.get_latest_task_cached()
  790. if not task:
  791. return {"success": True, "data": None}
  792. return {"success": True, "data": {"task_name": task["task_name"]}}
  793. except HTTPException:
  794. raise
  795. except Exception:
  796. logger.exception("获取 A/B LLM 任务失败")
  797. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  798. def _get_tutorial_intro_text(step: int) -> str | None:
  799. """根据教程步骤返回对应的固定英文文案。"""
  800. mapping: Dict[int, str] = {
  801. 1: "Hi! Nice to meet you, my friend. Let me show you my home.",
  802. 3: "I’ve added captions so we can understand each other even better!",
  803. 5: "Tap the button and let's talk! How was your day",
  804. 9: "You can see your Energy Stones here.",
  805. 10: "You can also see our Bond Level here. It shows how close we are.",
  806. 11: "That's all! let's start our first chat!",
  807. }
  808. return mapping.get(step)
  809. @app.get("/api/tutorials/{step}/intro-audio")
  810. async def get_tutorial_intro_audio(
  811. step: int,
  812. _: str = Depends(require_user_session_from_headers),
  813. ):
  814. """
  815. 新手教程步骤:返回对应字幕文案的 TTS 音频。
  816. - 支持步骤:1 / 3 / 5 / 9 / 10 / 11
  817. - 文案与前端字幕保持一致(ChatBotStaticShell 中的英文文案)
  818. - 使用全局 ai_service 进行 TTS 合成,返回单段 Base64 PCM。
  819. """
  820. text = _get_tutorial_intro_text(step)
  821. if text is None:
  822. raise HTTPException(status_code=404, detail={"code": GET_CONFIG_FAILED})
  823. try:
  824. audio_chunks: list[bytes] = []
  825. async for chunk in ai_service.text_to_speech_stream(text, emotion="friendly"):
  826. audio_chunks.append(chunk)
  827. if not audio_chunks:
  828. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  829. audio_bytes = b"".join(audio_chunks)
  830. audio_base64 = base64.b64encode(audio_bytes).decode("utf-8")
  831. return {
  832. "success": True,
  833. "data": {
  834. "audio": audio_base64,
  835. "sampleRate": 24000,
  836. "format": "pcm",
  837. "text": text,
  838. },
  839. }
  840. except HTTPException:
  841. raise
  842. except Exception as exc:
  843. logger.exception("生成教程步骤 TTS 音频失败: %s", exc)
  844. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  845. @app.get("/api/users/{user_id}/avatars")
  846. async def get_user_avatars(user_id: str, _: None = Depends(require_user_session)):
  847. """
  848. 获取用户已拥有的头像列表
  849. Args:
  850. user_id: 用户ID
  851. Returns:
  852. {
  853. "success": true,
  854. "data": {
  855. "avatar_ids": ["avatar_default", "avatar_registered_cap", ...]
  856. }
  857. }
  858. """
  859. try:
  860. async with db_manager.get_session() as session:
  861. result = await session.execute(
  862. select(UserAvatar.avatar_id).where(UserAvatar.user_id == user_id)
  863. )
  864. avatar_ids = [row[0] for row in result.fetchall()]
  865. return {
  866. "success": True,
  867. "data": {
  868. "avatar_ids": avatar_ids
  869. }
  870. }
  871. except Exception as e:
  872. logger.exception("获取用户头像信息失败")
  873. raise HTTPException(status_code=500, detail={"code": GET_AVATARS_FAILED})
  874. @app.get("/api/background-images")
  875. async def get_background_images():
  876. """
  877. 获取所有背景图片配置列表
  878. Returns:
  879. {
  880. "success": true,
  881. "data": [
  882. {
  883. "image_id": "default",
  884. "image_name": "默认背景",
  885. "image_url": "https://...",
  886. "thumbnail_url": "https://...",
  887. "unlock_type": "default",
  888. "display_order": 0,
  889. "is_active": true,
  890. ...
  891. },
  892. ...
  893. ]
  894. }
  895. """
  896. try:
  897. async with db_manager.get_session() as session:
  898. result = await session.execute(
  899. select(BackgroundImage).where(BackgroundImage.is_active == True).order_by(BackgroundImage.display_order)
  900. )
  901. background_images = result.scalars().all()
  902. return {
  903. "success": True,
  904. "data": [bg_image.to_dict() for bg_image in background_images]
  905. }
  906. except Exception as e:
  907. logger.error(f"获取背景图片配置失败: {e}")
  908. logger.exception("获取背景图片配置失败")
  909. raise HTTPException(status_code=500, detail={"code": GET_BG_CONFIG_FAILED})
  910. @app.get("/api/users/{user_id}/background-images")
  911. async def get_user_background_images(user_id: str, _: None = Depends(require_user_session)):
  912. """
  913. 获取用户已拥有的背景图片列表
  914. Args:
  915. user_id: 用户ID
  916. Returns:
  917. {
  918. "success": true,
  919. "data": {
  920. "image_ids": ["default", "happynewyear", ...]
  921. }
  922. }
  923. """
  924. try:
  925. async with db_manager.get_session() as session:
  926. result = await session.execute(
  927. select(UserBackgroundImage.image_id).where(UserBackgroundImage.user_id == user_id)
  928. )
  929. image_ids = [row[0] for row in result.fetchall()]
  930. return {
  931. "success": True,
  932. "data": {
  933. "image_ids": image_ids
  934. }
  935. }
  936. except Exception as e:
  937. logger.exception("获取用户背景图片信息失败")
  938. raise HTTPException(status_code=500, detail={"code": GET_USER_BG_IMAGES_FAILED})
  939. @app.get("/api/users/{user_id}/chatbot-layout")
  940. async def get_chatbot_layout(user_id: str, _: None = Depends(require_user_session)):
  941. """
  942. 获取用户 /chatbot 顶部装饰区布局(背景幕布 + 5x4 家具网格)
  943. 返回给前端用于动态渲染。
  944. """
  945. try:
  946. async with db_manager.get_session() as session:
  947. # 兼容:chatbot_layouts / user_chatbot_backdrops 表里的 user_id 可能是 BIGINT(users.id)
  948. # 也可能是 VARCHAR(users.user_id)。运行时探测信息架构来决定映射方式。
  949. async def _get_user_id_is_bigint(table_name: str) -> bool:
  950. res = await session.execute(
  951. text(
  952. """
  953. SELECT DATA_TYPE
  954. FROM information_schema.columns
  955. WHERE table_schema = :db
  956. AND table_name = :table
  957. AND column_name = 'user_id'
  958. """
  959. ),
  960. {"db": settings.MYSQL_DATABASE, "table": table_name},
  961. )
  962. row = res.mappings().first()
  963. data_type = (row or {}).get("DATA_TYPE") or ""
  964. return "bigint" in data_type.lower()
  965. layout_user_id_is_bigint = await _get_user_id_is_bigint("chatbot_layouts")
  966. backdrop_user_id_is_bigint = await _get_user_id_is_bigint("user_chatbot_backdrops")
  967. layout_user_id_where_expr = (
  968. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  969. if layout_user_id_is_bigint
  970. else ":user_id"
  971. )
  972. backdrop_user_id_where_expr = (
  973. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  974. if backdrop_user_id_is_bigint
  975. else ":user_id"
  976. )
  977. layout_row_res = await session.execute(
  978. text(
  979. f"""
  980. SELECT
  981. id,
  982. grid_rows,
  983. grid_cols,
  984. cell_width,
  985. cell_height,
  986. decor_area_width,
  987. decor_area_height,
  988. updated_at
  989. FROM chatbot_layouts l
  990. WHERE l.user_id = {layout_user_id_where_expr}
  991. ORDER BY l.updated_at DESC, l.id DESC
  992. LIMIT 1
  993. """
  994. ),
  995. {"user_id": user_id},
  996. )
  997. layout_row = layout_row_res.mappings().first()
  998. backdrop_res = await session.execute(
  999. text(
  1000. f"""
  1001. SELECT
  1002. ub.z_index,
  1003. ub.backdrop_item_id,
  1004. COALESCE(NULLIF(TRIM(si.render_image_name), ''), si.image_name) AS image_name
  1005. FROM user_chatbot_backdrops ub
  1006. JOIN shop_items si
  1007. ON ub.backdrop_item_id = si.id
  1008. WHERE ub.user_id = {backdrop_user_id_where_expr}
  1009. ORDER BY ub.z_index DESC, ub.id DESC
  1010. LIMIT 1
  1011. """
  1012. ),
  1013. {"user_id": user_id},
  1014. )
  1015. backdrop_row = backdrop_res.mappings().first()
  1016. current_backdrop_item_id = (
  1017. int(backdrop_row["backdrop_item_id"])
  1018. if backdrop_row and backdrop_row.get("backdrop_item_id") is not None
  1019. else None
  1020. )
  1021. async def _table_exists(table_name: str) -> bool:
  1022. res = await session.execute(
  1023. text(
  1024. """
  1025. SELECT COUNT(*) AS c
  1026. FROM information_schema.tables
  1027. WHERE table_schema = :db
  1028. AND table_name = :table
  1029. """
  1030. ),
  1031. {"db": settings.MYSQL_DATABASE, "table": table_name},
  1032. )
  1033. row = res.mappings().first()
  1034. return bool(row and int(row.get("c") or 0) > 0)
  1035. items: list[dict[str, Any]] = []
  1036. slots: list[dict[str, Any]] = []
  1037. has_new_slot_tables = (
  1038. await _table_exists("user_chatbot_slot_placements")
  1039. and await _table_exists("chatbot_backdrop_slots")
  1040. )
  1041. if has_new_slot_tables and current_backdrop_item_id is not None:
  1042. slots_res = await session.execute(
  1043. text(
  1044. """
  1045. SELECT
  1046. s.id,
  1047. s.slot_code,
  1048. s.placement_type,
  1049. s.start_row,
  1050. s.start_col,
  1051. s.size_rows,
  1052. s.size_cols,
  1053. COALESCE(s.z_index, 0) AS z_index,
  1054. s.render_mode,
  1055. s.offset_x,
  1056. s.offset_y,
  1057. s.pixel_width,
  1058. s.pixel_height
  1059. FROM chatbot_backdrop_slots s
  1060. WHERE s.backdrop_item_id = :backdrop_item_id
  1061. AND s.is_active = 1
  1062. ORDER BY COALESCE(s.z_index, 0) ASC, s.id ASC
  1063. """
  1064. ),
  1065. {"backdrop_item_id": current_backdrop_item_id},
  1066. )
  1067. slots = [dict(r) for r in slots_res.mappings().all()]
  1068. slot_items_res = await session.execute(
  1069. text(
  1070. f"""
  1071. SELECT
  1072. usp.id,
  1073. usp.slot_code AS slot_code,
  1074. s.placement_type,
  1075. s.start_row,
  1076. s.start_col,
  1077. s.size_rows,
  1078. s.size_cols,
  1079. COALESCE(usp.z_index, s.z_index, si.default_z_index, 0) AS z_index,
  1080. usp.image_name_snapshot,
  1081. usp.item_id,
  1082. COALESCE(si.scene_anchor_type, 'none') AS scene_anchor_type,
  1083. s.render_mode,
  1084. s.offset_x,
  1085. s.offset_y,
  1086. s.pixel_width,
  1087. s.pixel_height
  1088. FROM user_chatbot_slot_placements usp
  1089. JOIN chatbot_backdrop_slots s
  1090. ON s.backdrop_item_id = usp.backdrop_item_id
  1091. AND s.slot_code = usp.slot_code
  1092. AND s.is_active = 1
  1093. LEFT JOIN shop_items si ON si.id = usp.item_id
  1094. WHERE usp.user_id = {layout_user_id_where_expr}
  1095. AND usp.backdrop_item_id = :backdrop_item_id
  1096. ORDER BY COALESCE(usp.z_index, s.z_index, si.default_z_index, 0) ASC, usp.id ASC
  1097. """
  1098. ),
  1099. {"user_id": user_id, "backdrop_item_id": current_backdrop_item_id},
  1100. )
  1101. items = [dict(r) for r in slot_items_res.mappings().all()]
  1102. # 兼容旧模型(灰度期间):新槽位数据为空时回退旧的 chatbot_layout_items
  1103. if not items and layout_row and layout_row.get("id") is not None:
  1104. layout_id = layout_row["id"]
  1105. items_res = await session.execute(
  1106. text(
  1107. """
  1108. SELECT
  1109. li.id,
  1110. li.placement_type,
  1111. li.start_row,
  1112. li.start_col,
  1113. li.size_rows,
  1114. li.size_cols,
  1115. li.z_index,
  1116. li.image_name_snapshot,
  1117. li.item_id,
  1118. COALESCE(si.scene_anchor_type, 'none') AS scene_anchor_type,
  1119. 'grid' AS render_mode,
  1120. 0 AS offset_x,
  1121. 0 AS offset_y,
  1122. NULL AS pixel_width,
  1123. NULL AS pixel_height
  1124. FROM chatbot_layout_items li
  1125. LEFT JOIN shop_items si ON si.id = li.item_id
  1126. WHERE li.layout_id = :layout_id
  1127. ORDER BY li.z_index ASC, li.id ASC
  1128. """
  1129. ),
  1130. {"layout_id": layout_id},
  1131. )
  1132. items = [dict(r) for r in items_res.mappings().all()]
  1133. data: dict[str, Any] = {
  1134. "grid_rows": int(layout_row.get("grid_rows")) if layout_row else 5,
  1135. "grid_cols": int(layout_row.get("grid_cols")) if layout_row else 4,
  1136. "cell_width": int(layout_row.get("cell_width")) if layout_row else 96,
  1137. "cell_height": int(layout_row.get("cell_height")) if layout_row else 96,
  1138. "decor_area_width": int(layout_row.get("decor_area_width")) if layout_row else 393,
  1139. "decor_area_height": int(layout_row.get("decor_area_height")) if layout_row else 482,
  1140. "backdrop": None,
  1141. "items": items,
  1142. "slots": slots,
  1143. }
  1144. if backdrop_row and backdrop_row.get("image_name"):
  1145. data["backdrop"] = {
  1146. "image_name": backdrop_row["image_name"],
  1147. "z_index": int(backdrop_row.get("z_index") or 0),
  1148. }
  1149. return {"success": True, "data": data}
  1150. except Exception as exc: # noqa: BLE001
  1151. logger.exception("获取用户 /chatbot 布局失败: %s", exc)
  1152. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  1153. async def _mysql_user_id_column_is_bigint(session, table_name: str) -> bool:
  1154. res = await session.execute(
  1155. text(
  1156. """
  1157. SELECT DATA_TYPE
  1158. FROM information_schema.columns
  1159. WHERE table_schema = :db
  1160. AND table_name = :table
  1161. AND column_name = 'user_id'
  1162. """
  1163. ),
  1164. {"db": settings.MYSQL_DATABASE, "table": table_name},
  1165. )
  1166. row = res.mappings().first()
  1167. data_type = (row or {}).get("DATA_TYPE") or ""
  1168. return "bigint" in str(data_type).lower()
  1169. async def _chatbot_in_use_item_ids(session, user_id: str) -> set[int]:
  1170. """当前幕布 + 槽位/布局中已装备的 shop_items.id 集合。"""
  1171. layout_user_id_expr = (
  1172. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  1173. if await _mysql_user_id_column_is_bigint(session, "chatbot_layouts")
  1174. else ":user_id"
  1175. )
  1176. backdrop_user_id_expr = (
  1177. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  1178. if await _mysql_user_id_column_is_bigint(session, "user_chatbot_backdrops")
  1179. else ":user_id"
  1180. )
  1181. current_backdrop_res = await session.execute(
  1182. text(
  1183. f"""
  1184. SELECT ub.backdrop_item_id
  1185. FROM user_chatbot_backdrops ub
  1186. WHERE ub.user_id = {backdrop_user_id_expr}
  1187. ORDER BY ub.updated_at DESC, ub.id DESC
  1188. LIMIT 1
  1189. """
  1190. ),
  1191. {"user_id": user_id},
  1192. )
  1193. current_backdrop_row = current_backdrop_res.mappings().first()
  1194. current_backdrop_item_id = (
  1195. int(current_backdrop_row["backdrop_item_id"])
  1196. if current_backdrop_row and current_backdrop_row.get("backdrop_item_id") is not None
  1197. else None
  1198. )
  1199. in_use_item_ids: set[int] = set()
  1200. if current_backdrop_item_id is not None:
  1201. in_use_item_ids.add(current_backdrop_item_id)
  1202. slot_table_res = await session.execute(
  1203. text(
  1204. """
  1205. SELECT COUNT(*) AS c
  1206. FROM information_schema.tables
  1207. WHERE table_schema = :db
  1208. AND table_name = 'user_chatbot_slot_placements'
  1209. """
  1210. ),
  1211. {"db": settings.MYSQL_DATABASE},
  1212. )
  1213. has_slot_table = int((slot_table_res.mappings().first() or {}).get("c") or 0) > 0
  1214. if has_slot_table and current_backdrop_item_id is not None:
  1215. slot_items_res = await session.execute(
  1216. text(
  1217. f"""
  1218. SELECT DISTINCT usp.item_id
  1219. FROM user_chatbot_slot_placements usp
  1220. WHERE usp.user_id = {layout_user_id_expr}
  1221. AND usp.backdrop_item_id = :backdrop_item_id
  1222. AND usp.item_id IS NOT NULL
  1223. """
  1224. ),
  1225. {"user_id": user_id, "backdrop_item_id": current_backdrop_item_id},
  1226. )
  1227. for row in slot_items_res.mappings().all():
  1228. iid = row.get("item_id")
  1229. if iid is not None:
  1230. in_use_item_ids.add(int(iid))
  1231. else:
  1232. latest_layout_res = await session.execute(
  1233. text(
  1234. f"""
  1235. SELECT l.id
  1236. FROM chatbot_layouts l
  1237. WHERE l.user_id = {layout_user_id_expr}
  1238. ORDER BY l.updated_at DESC, l.id DESC
  1239. LIMIT 1
  1240. """
  1241. ),
  1242. {"user_id": user_id},
  1243. )
  1244. latest_layout_row = latest_layout_res.mappings().first()
  1245. if latest_layout_row and latest_layout_row.get("id") is not None:
  1246. layout_item_res = await session.execute(
  1247. text(
  1248. """
  1249. SELECT DISTINCT li.item_id
  1250. FROM chatbot_layout_items li
  1251. WHERE li.layout_id = :layout_id
  1252. AND li.item_id IS NOT NULL
  1253. """
  1254. ),
  1255. {"layout_id": int(latest_layout_row["id"])},
  1256. )
  1257. for row in layout_item_res.mappings().all():
  1258. iid = row.get("item_id")
  1259. if iid is not None:
  1260. in_use_item_ids.add(int(iid))
  1261. return in_use_item_ids
  1262. @app.get("/api/users/{user_id}/chatbot-owned-items")
  1263. async def get_chatbot_owned_items(user_id: str, _: None = Depends(require_user_session)):
  1264. """获取用户已拥有的 ChatBot 商品(家具 + 幕布),用于前端背包展示。"""
  1265. try:
  1266. async with db_manager.get_session() as session:
  1267. assets_user_id_expr = (
  1268. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  1269. if await _mysql_user_id_column_is_bigint(session, "user_assets")
  1270. else ":user_id"
  1271. )
  1272. in_use_item_ids = await _chatbot_in_use_item_ids(session, user_id)
  1273. owned_res = await session.execute(
  1274. text(
  1275. f"""
  1276. SELECT
  1277. si.id,
  1278. si.item_code,
  1279. si.name,
  1280. si.name_zh,
  1281. si.name_en,
  1282. si.has_special_scene_trigger,
  1283. si.image_name,
  1284. si.render_image_name,
  1285. si.item_type,
  1286. si.biz_type,
  1287. si.sort_order
  1288. FROM user_assets ua
  1289. JOIN shop_items si
  1290. ON si.id = ua.item_id
  1291. WHERE ua.user_id = {assets_user_id_expr}
  1292. AND ua.owned_qty > 0
  1293. AND si.is_active = 1
  1294. AND si.item_type IN ('furniture', 'backdrop')
  1295. ORDER BY si.sort_order ASC, si.id ASC
  1296. """
  1297. ),
  1298. {"user_id": user_id},
  1299. )
  1300. rows = owned_res.mappings().all()
  1301. return {
  1302. "success": True,
  1303. "data": [
  1304. {
  1305. "item_id": int(r["id"]),
  1306. "item_code": r.get("item_code"),
  1307. "name": r.get("name"),
  1308. "name_zh": r.get("name_zh"),
  1309. "name_en": r.get("name_en"),
  1310. "has_special_scene_trigger": int(r.get("has_special_scene_trigger") or 0),
  1311. "image_name": r.get("image_name"),
  1312. "render_image_name": r.get("render_image_name"),
  1313. "item_type": r.get("item_type"),
  1314. "biz_type": r.get("biz_type"),
  1315. "is_in_use": int(r["id"]) in in_use_item_ids,
  1316. }
  1317. for r in rows
  1318. ],
  1319. }
  1320. except Exception as exc: # noqa: BLE001
  1321. logger.exception("获取用户已购商品失败: %s", exc)
  1322. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  1323. @app.get("/api/users/{user_id}/chatbot-shop-catalog")
  1324. async def get_chatbot_shop_catalog(user_id: str, _: None = Depends(require_user_session)):
  1325. """上架中的家具 + 幕布全库(含是否已拥有、是否当前使用中),用于 Lumi 商店等场景。"""
  1326. try:
  1327. async with db_manager.get_session() as session:
  1328. assets_user_id_expr = (
  1329. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  1330. if await _mysql_user_id_column_is_bigint(session, "user_assets")
  1331. else ":user_id"
  1332. )
  1333. in_use_item_ids = await _chatbot_in_use_item_ids(session, user_id)
  1334. catalog_res = await session.execute(
  1335. text(
  1336. f"""
  1337. SELECT
  1338. si.id,
  1339. si.item_code,
  1340. si.name,
  1341. si.name_zh,
  1342. si.name_en,
  1343. si.has_special_scene_trigger,
  1344. si.image_name,
  1345. si.render_image_name,
  1346. si.item_type,
  1347. si.biz_type,
  1348. si.sort_order,
  1349. si.price_energy,
  1350. si.max_per_user,
  1351. si.repeat_purchase_mode,
  1352. COALESCE(ua.owned_qty, 0) AS owned_qty,
  1353. CASE
  1354. WHEN COALESCE(ua.owned_qty, 0) > 0 THEN 1
  1355. ELSE 0
  1356. END AS is_owned
  1357. FROM shop_items si
  1358. LEFT JOIN user_assets ua
  1359. ON ua.item_id = si.id
  1360. AND ua.user_id = {assets_user_id_expr}
  1361. WHERE si.is_active = 1
  1362. AND si.item_type IN ('furniture', 'backdrop')
  1363. ORDER BY si.sort_order ASC, si.id ASC
  1364. """
  1365. ),
  1366. {"user_id": user_id},
  1367. )
  1368. rows = catalog_res.mappings().all()
  1369. return {
  1370. "success": True,
  1371. "data": [
  1372. {
  1373. "item_id": int(r["id"]),
  1374. "item_code": r.get("item_code"),
  1375. "name": r.get("name"),
  1376. "name_zh": r.get("name_zh"),
  1377. "name_en": r.get("name_en"),
  1378. "has_special_scene_trigger": int(r.get("has_special_scene_trigger") or 0),
  1379. "image_name": r.get("image_name"),
  1380. "render_image_name": r.get("render_image_name"),
  1381. "item_type": r.get("item_type"),
  1382. "biz_type": r.get("biz_type"),
  1383. "is_in_use": int(r["id"]) in in_use_item_ids,
  1384. "is_owned": bool(int(r.get("is_owned") or 0)),
  1385. "price_energy": float(r.get("price_energy") or 0),
  1386. "max_per_user": (
  1387. int(r["max_per_user"])
  1388. if r.get("max_per_user") is not None
  1389. else None
  1390. ),
  1391. "owned_qty": int(r.get("owned_qty") or 0),
  1392. "repeat_purchase_mode": r.get("repeat_purchase_mode") or "single",
  1393. }
  1394. for r in rows
  1395. ],
  1396. }
  1397. except Exception as exc: # noqa: BLE001
  1398. logger.exception("获取 ChatBot 商品库失败: %s", exc)
  1399. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  1400. @app.get("/api/users/{user_id}/chatbot-shop-cart")
  1401. async def get_chatbot_shop_cart(user_id: str, _: None = Depends(require_user_session)):
  1402. """用户 ChatBot 商店购物车(家具/幕布)。"""
  1403. try:
  1404. async with db_manager.get_session() as session:
  1405. user_row = await session.execute(
  1406. text("SELECT id FROM users WHERE user_id = :user_id LIMIT 1"),
  1407. {"user_id": user_id},
  1408. )
  1409. ur = user_row.mappings().first()
  1410. if not ur:
  1411. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  1412. internal_uid = int(ur["id"])
  1413. cart_res = await session.execute(
  1414. text(
  1415. """
  1416. SELECT id FROM shopping_carts
  1417. WHERE user_id = :uid
  1418. ORDER BY id ASC
  1419. LIMIT 1
  1420. """
  1421. ),
  1422. {"uid": internal_uid, "user_id": user_id},
  1423. )
  1424. cart_row = cart_res.mappings().first()
  1425. if not cart_row:
  1426. return {"success": True, "data": {"items": [], "cart_total_quantity": 0}}
  1427. cart_id = int(cart_row["id"])
  1428. items_res = await session.execute(
  1429. text(
  1430. """
  1431. SELECT item_id, quantity, unit_price_energy, unit_price_crystal
  1432. FROM shopping_cart_items
  1433. WHERE cart_id = :cid
  1434. ORDER BY id ASC
  1435. """
  1436. ),
  1437. {"cid": cart_id},
  1438. )
  1439. rows = items_res.mappings().all()
  1440. items = [
  1441. {
  1442. "item_id": int(r["item_id"]),
  1443. "quantity": int(r.get("quantity") or 0),
  1444. "unit_price_energy": float(r.get("unit_price_energy") or 0),
  1445. "unit_price_crystal": float(r.get("unit_price_crystal") or 0),
  1446. }
  1447. for r in rows
  1448. ]
  1449. total_q = sum(i["quantity"] for i in items)
  1450. return {"success": True, "data": {"items": items, "cart_total_quantity": total_q}}
  1451. except HTTPException:
  1452. raise
  1453. except Exception as exc: # noqa: BLE001
  1454. logger.exception("获取 ChatBot 购物车失败: %s", exc)
  1455. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  1456. @app.post("/api/users/{user_id}/chatbot-shop-cart/add")
  1457. async def add_chatbot_shop_cart_item(
  1458. user_id: str,
  1459. request: ChatbotShopCartAddRequest,
  1460. _: None = Depends(require_user_session),
  1461. ):
  1462. """上架家具/幕布加入购物车;数量与已购合计不得超过 shop_items.max_per_user(若有限)。"""
  1463. try:
  1464. async with db_manager.get_session() as session:
  1465. assets_user_id_expr = (
  1466. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  1467. if await _mysql_user_id_column_is_bigint(session, "user_assets")
  1468. else ":user_id"
  1469. )
  1470. user_row = await session.execute(
  1471. text("SELECT id FROM users WHERE user_id = :user_id LIMIT 1"),
  1472. {"user_id": user_id},
  1473. )
  1474. ur = user_row.mappings().first()
  1475. if not ur:
  1476. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  1477. internal_uid = int(ur["id"])
  1478. item_res = await session.execute(
  1479. text(
  1480. """
  1481. SELECT
  1482. id,
  1483. price_energy,
  1484. price_crystal,
  1485. max_per_user,
  1486. repeat_purchase_mode,
  1487. is_active,
  1488. item_type
  1489. FROM shop_items
  1490. WHERE id = :item_id
  1491. LIMIT 1
  1492. """
  1493. ),
  1494. {"item_id": request.item_id},
  1495. )
  1496. item_row = item_res.mappings().first()
  1497. if not item_row or int(item_row.get("is_active") or 0) != 1:
  1498. raise HTTPException(status_code=404, detail={"code": SHOP_ITEM_NOT_FOUND})
  1499. if str(item_row.get("item_type") or "") not in ("furniture", "backdrop"):
  1500. raise HTTPException(status_code=404, detail={"code": SHOP_ITEM_NOT_FOUND})
  1501. owned_res = await session.execute(
  1502. text(
  1503. f"""
  1504. SELECT COALESCE(ua.owned_qty, 0) AS owned_qty
  1505. FROM shop_items si
  1506. LEFT JOIN user_assets ua
  1507. ON ua.item_id = si.id
  1508. AND ua.user_id = {assets_user_id_expr}
  1509. WHERE si.id = :item_id
  1510. LIMIT 1
  1511. """
  1512. ),
  1513. {"user_id": user_id, "item_id": request.item_id},
  1514. )
  1515. owned_qty = int((owned_res.mappings().first() or {}).get("owned_qty") or 0)
  1516. repeat_mode = str(item_row.get("repeat_purchase_mode") or "single")
  1517. if repeat_mode == "single" and owned_qty >= 1:
  1518. raise HTTPException(status_code=400, detail={"code": PURCHASE_LIMIT_REACHED})
  1519. cart_res = await session.execute(
  1520. text(
  1521. """
  1522. SELECT id FROM shopping_carts
  1523. WHERE user_id = :uid
  1524. ORDER BY id ASC
  1525. LIMIT 1
  1526. """
  1527. ),
  1528. {"uid": internal_uid},
  1529. )
  1530. cart_row = cart_res.mappings().first()
  1531. if not cart_row:
  1532. await session.execute(
  1533. text("INSERT INTO shopping_carts (user_id) VALUES (:uid)"),
  1534. {"uid": internal_uid},
  1535. )
  1536. oid_ins = await session.execute(text("SELECT LAST_INSERT_ID() AS cid"))
  1537. cart_id = int(oid_ins.scalar_one() or 0)
  1538. else:
  1539. cart_id = int(cart_row["id"])
  1540. line_res = await session.execute(
  1541. text(
  1542. """
  1543. SELECT id, quantity FROM shopping_cart_items
  1544. WHERE cart_id = :cid AND item_id = :item_id
  1545. LIMIT 1
  1546. """
  1547. ),
  1548. {"cid": cart_id, "item_id": request.item_id},
  1549. )
  1550. line = line_res.mappings().first()
  1551. current_cart_qty = int(line.get("quantity") or 0) if line else 0
  1552. new_cart_qty = current_cart_qty + 1
  1553. max_per = item_row.get("max_per_user")
  1554. max_per_int = int(max_per) if max_per is not None else None
  1555. if max_per_int is not None and owned_qty + new_cart_qty > max_per_int:
  1556. raise HTTPException(status_code=400, detail={"code": CART_QUANTITY_LIMIT_EXCEEDED})
  1557. try:
  1558. pe = Decimal(str(item_row.get("price_energy") or 0))
  1559. pc = Decimal(str(item_row.get("price_crystal") or 0))
  1560. except (ArithmeticError, ValueError, TypeError):
  1561. pe = Decimal("0")
  1562. pc = Decimal("0")
  1563. if line:
  1564. await session.execute(
  1565. text(
  1566. """
  1567. UPDATE shopping_cart_items
  1568. SET quantity = :q, updated_at = NOW()
  1569. WHERE id = :id
  1570. """
  1571. ),
  1572. {"q": new_cart_qty, "id": int(line["id"])},
  1573. )
  1574. else:
  1575. await session.execute(
  1576. text(
  1577. """
  1578. INSERT INTO shopping_cart_items
  1579. (cart_id, item_id, quantity, unit_price_energy, unit_price_crystal)
  1580. VALUES
  1581. (:cid, :iid, 1, :pe, :pc)
  1582. """
  1583. ),
  1584. {"cid": cart_id, "iid": int(request.item_id), "pe": pe, "pc": pc},
  1585. )
  1586. sum_res = await session.execute(
  1587. text(
  1588. """
  1589. SELECT COALESCE(SUM(quantity), 0) AS tq
  1590. FROM shopping_cart_items
  1591. WHERE cart_id = :cid
  1592. """
  1593. ),
  1594. {"cid": cart_id},
  1595. )
  1596. cart_total = int(sum_res.scalar_one() or 0)
  1597. await session.commit()
  1598. return {
  1599. "success": True,
  1600. "data": {
  1601. "item_id": int(request.item_id),
  1602. "item_quantity": new_cart_qty,
  1603. "cart_total_quantity": cart_total,
  1604. },
  1605. }
  1606. except HTTPException:
  1607. raise
  1608. except Exception as exc: # noqa: BLE001
  1609. logger.exception("ChatBot 购物车加购失败: %s", exc)
  1610. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  1611. @app.post("/api/users/{user_id}/chatbot-shop-cart/remove")
  1612. async def remove_chatbot_shop_cart_item(
  1613. user_id: str,
  1614. request: ChatbotShopCartRemoveRequest,
  1615. _: None = Depends(require_user_session),
  1616. ):
  1617. """移除购物车中的家具/幕布商品(删除该 item 的购物车行)"""
  1618. try:
  1619. async with db_manager.get_session() as session:
  1620. assets_user_id_expr = (
  1621. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  1622. if await _mysql_user_id_column_is_bigint(session, "user_assets")
  1623. else ":user_id"
  1624. )
  1625. user_row = await session.execute(
  1626. text("SELECT id FROM users WHERE user_id = :user_id LIMIT 1"),
  1627. {"user_id": user_id},
  1628. )
  1629. ur = user_row.mappings().first()
  1630. if not ur:
  1631. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  1632. internal_uid = int(ur["id"])
  1633. await session.execute(
  1634. text(
  1635. """
  1636. DELETE sci
  1637. FROM shopping_cart_items sci
  1638. INNER JOIN shopping_carts sc ON sc.id = sci.cart_id
  1639. WHERE sc.user_id = :uid
  1640. AND sci.item_id = :item_id
  1641. """
  1642. ),
  1643. {"uid": internal_uid, "item_id": int(request.item_id)},
  1644. )
  1645. sum_res = await session.execute(
  1646. text(
  1647. """
  1648. SELECT COALESCE(SUM(sci.quantity), 0) AS tq
  1649. FROM shopping_cart_items sci
  1650. INNER JOIN shopping_carts sc ON sc.id = sci.cart_id
  1651. WHERE sc.user_id = :uid
  1652. """
  1653. ),
  1654. {"uid": internal_uid},
  1655. )
  1656. cart_total = int(sum_res.scalar_one() or 0)
  1657. await session.commit()
  1658. return {
  1659. "success": True,
  1660. "data": {"item_id": int(request.item_id), "cart_total_quantity": cart_total},
  1661. }
  1662. except HTTPException:
  1663. raise
  1664. except Exception as exc: # noqa: BLE001
  1665. logger.exception("ChatBot 移除购物车失败: %s", exc)
  1666. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  1667. @app.post("/api/users/{user_id}/chatbot-shop-cart/purchase")
  1668. async def purchase_chatbot_shop_cart_item(
  1669. user_id: str,
  1670. request: ChatbotShopCartPurchaseRequest,
  1671. _: None = Depends(require_user_session),
  1672. ):
  1673. """购买购物车中的所有家具/幕布商品(一次性校验与扣费)"""
  1674. try:
  1675. async with db_manager.get_session() as session:
  1676. assets_user_id_expr = (
  1677. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  1678. if await _mysql_user_id_column_is_bigint(session, "user_assets")
  1679. else ":user_id"
  1680. )
  1681. user_row = await session.execute(
  1682. text("SELECT id FROM users WHERE user_id = :user_id LIMIT 1"),
  1683. {"user_id": user_id},
  1684. )
  1685. ur = user_row.mappings().first()
  1686. if not ur:
  1687. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  1688. internal_uid = int(ur["id"])
  1689. cart_res = await session.execute(
  1690. text(
  1691. """
  1692. SELECT id FROM shopping_carts
  1693. WHERE user_id = :uid
  1694. ORDER BY id ASC
  1695. LIMIT 1
  1696. """
  1697. ),
  1698. {"uid": internal_uid},
  1699. )
  1700. cart_row = cart_res.mappings().first()
  1701. if not cart_row:
  1702. return {"success": True, "data": {"total_quantity": 0, "total_cost_energy": 0}}
  1703. cart_id = int(cart_row["id"])
  1704. cart_lines_res = await session.execute(
  1705. text(
  1706. f"""
  1707. SELECT
  1708. sci.item_id,
  1709. sci.quantity AS cart_qty,
  1710. si.price_energy,
  1711. si.price_crystal,
  1712. si.max_per_user,
  1713. si.repeat_purchase_mode,
  1714. si.is_active,
  1715. si.item_type,
  1716. si.name,
  1717. si.image_name,
  1718. COALESCE(ua.owned_qty, 0) AS owned_qty
  1719. FROM shopping_cart_items sci
  1720. INNER JOIN shopping_carts sc ON sc.id = sci.cart_id
  1721. INNER JOIN shop_items si ON si.id = sci.item_id
  1722. LEFT JOIN user_assets ua
  1723. ON ua.item_id = si.id
  1724. AND ua.user_id = {assets_user_id_expr}
  1725. WHERE sc.user_id = :uid
  1726. ORDER BY sci.id ASC
  1727. """
  1728. ),
  1729. {"uid": internal_uid, "user_id": user_id},
  1730. )
  1731. cart_lines = cart_lines_res.mappings().all()
  1732. if not cart_lines:
  1733. return {"success": True, "data": {"total_quantity": 0, "total_cost_energy": 0}}
  1734. # 预校验:限购/重复模式 + 总价校验(在写入前完成,避免部分成功)
  1735. total_qty = 0
  1736. total_cost_energy = 0
  1737. for r in cart_lines:
  1738. item_id = int(r["item_id"])
  1739. cart_qty = int(r.get("cart_qty") or 0)
  1740. if cart_qty <= 0:
  1741. continue
  1742. if str(r.get("is_active") or 0) != "1":
  1743. raise HTTPException(status_code=404, detail={"code": SHOP_ITEM_NOT_FOUND})
  1744. if str(r.get("item_type") or "") not in ("furniture", "backdrop"):
  1745. raise HTTPException(status_code=404, detail={"code": SHOP_ITEM_NOT_FOUND})
  1746. owned_qty = int(r.get("owned_qty") or 0)
  1747. max_per = r.get("max_per_user")
  1748. max_per_int = int(max_per) if max_per is not None else None
  1749. if max_per_int is not None and owned_qty + cart_qty > max_per_int:
  1750. raise HTTPException(status_code=400, detail={"code": CART_QUANTITY_LIMIT_EXCEEDED})
  1751. repeat_mode = str(r.get("repeat_purchase_mode") or "single")
  1752. # repeat_purchase_mode=single:用户购买后即无法再购买
  1753. if repeat_mode == "single" and owned_qty + cart_qty > 1:
  1754. raise HTTPException(status_code=400, detail={"code": PURCHASE_LIMIT_REACHED})
  1755. unit_cost_energy = _floor_shop_price_energy(r.get("price_energy"))
  1756. total_qty += cart_qty
  1757. total_cost_energy += unit_cost_energy * cart_qty
  1758. # 校验余额并扣费
  1759. bal_res = await session.execute(
  1760. text(
  1761. """
  1762. SELECT id, conversation_energy_stone_total
  1763. FROM users
  1764. WHERE user_id = :user_id
  1765. LIMIT 1
  1766. """
  1767. ),
  1768. {"user_id": user_id},
  1769. )
  1770. bal_row = bal_res.mappings().first()
  1771. if not bal_row:
  1772. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  1773. balance = int(bal_row.get("conversation_energy_stone_total") or 0)
  1774. if total_cost_energy > balance:
  1775. raise HTTPException(status_code=400, detail={"code": INSUFFICIENT_CONVERSATION_ENERGY})
  1776. upd_res = await session.execute(
  1777. text(
  1778. """
  1779. UPDATE users
  1780. SET conversation_energy_stone_total = conversation_energy_stone_total - :cost
  1781. WHERE user_id = :user_id
  1782. AND conversation_energy_stone_total >= :cost
  1783. """
  1784. ),
  1785. {"cost": total_cost_energy, "user_id": user_id},
  1786. )
  1787. if (getattr(upd_res, "rowcount", None) or 0) < 1:
  1788. raise HTTPException(status_code=400, detail={"code": INSUFFICIENT_CONVERSATION_ENERGY})
  1789. # 写入订单 + 更新拥有量 + 清空购物车(仍在同一事务里)
  1790. await session.execute(
  1791. text(
  1792. """
  1793. INSERT INTO purchase_orders
  1794. (user_id, cart_id, status, total_quantity, total_cost_energy, total_cost_crystal, completed_at)
  1795. VALUES
  1796. (:uid, :cart_id, 'completed', :total_quantity, :tce, 0.00, NOW())
  1797. """
  1798. ),
  1799. {
  1800. "uid": internal_uid,
  1801. "cart_id": cart_id,
  1802. "total_quantity": total_qty,
  1803. "tce": Decimal(str(total_cost_energy)),
  1804. },
  1805. )
  1806. oid_row = await session.execute(text("SELECT LAST_INSERT_ID() AS oid"))
  1807. order_id_raw = oid_row.scalar_one()
  1808. order_id = int(order_id_raw) if order_id_raw is not None else 0
  1809. if order_id <= 0:
  1810. raise RuntimeError("purchase_orders insert did not return id")
  1811. # 更新用户资产:逐条处理,避免不同 item 存在差异导致 SQL 复杂化
  1812. for r in cart_lines:
  1813. item_id = int(r["item_id"])
  1814. cart_qty = int(r.get("cart_qty") or 0)
  1815. if cart_qty <= 0:
  1816. continue
  1817. owned_qty = int(r.get("owned_qty") or 0)
  1818. max_per = r.get("max_per_user")
  1819. max_per_int = int(max_per) if max_per is not None else None
  1820. # owned_qty 已在预校验阶段确认;这里不再重复校验,保证业务逻辑一致
  1821. unit_cost_energy = _floor_shop_price_energy(r.get("price_energy"))
  1822. unit_pe = Decimal(str(unit_cost_energy))
  1823. try:
  1824. unit_pc = Decimal(str(r.get("price_crystal")) if r.get("price_crystal") is not None else "0")
  1825. except (ArithmeticError, ValueError, TypeError):
  1826. unit_pc = Decimal("0")
  1827. chk = await session.execute(
  1828. text(
  1829. f"""
  1830. SELECT id FROM user_assets
  1831. WHERE user_id = {assets_user_id_expr} AND item_id = :item_id
  1832. LIMIT 1
  1833. """
  1834. ),
  1835. {"user_id": user_id, "item_id": item_id},
  1836. )
  1837. existing_uaid = chk.scalar_one_or_none()
  1838. if existing_uaid is not None:
  1839. await session.execute(
  1840. text(
  1841. """
  1842. UPDATE user_assets
  1843. SET owned_qty = owned_qty + :q,
  1844. last_acquired_at = NOW(),
  1845. updated_at = NOW()
  1846. WHERE id = :id
  1847. """
  1848. ),
  1849. {"q": cart_qty, "id": int(existing_uaid)},
  1850. )
  1851. else:
  1852. await session.execute(
  1853. text(
  1854. f"""
  1855. INSERT INTO user_assets
  1856. (user_id, item_id, owned_qty, used_qty, last_acquired_at, created_at, updated_at)
  1857. VALUES
  1858. ({assets_user_id_expr}, :item_id, :q, 0, NOW(), NOW(), NOW())
  1859. """
  1860. ),
  1861. {"user_id": user_id, "item_id": item_id, "q": cart_qty},
  1862. )
  1863. item_name_snap = str(r.get("name") or "")[:100]
  1864. image_name_snap = str(r.get("image_name") or "")[:255]
  1865. await session.execute(
  1866. text(
  1867. """
  1868. INSERT INTO purchase_order_items
  1869. (order_id, item_id, quantity, unit_price_energy, unit_price_crystal,
  1870. cost_energy, cost_crystal, item_name_snapshot, image_name_snapshot)
  1871. VALUES
  1872. (:order_id, :item_id, :qty, :upe, :upc, :ce, 0.00, :name_snap, :img_snap)
  1873. """
  1874. ),
  1875. {
  1876. "order_id": order_id,
  1877. "item_id": item_id,
  1878. "qty": cart_qty,
  1879. "upe": unit_pe,
  1880. "upc": unit_pc,
  1881. "ce": unit_pe * cart_qty,
  1882. "name_snap": item_name_snap,
  1883. "img_snap": image_name_snap,
  1884. },
  1885. )
  1886. # 清空购物车(该 cart_id 下的所有行)
  1887. await session.execute(
  1888. text(
  1889. """
  1890. DELETE sci
  1891. FROM shopping_cart_items sci
  1892. INNER JOIN shopping_carts sc ON sc.id = sci.cart_id
  1893. WHERE sc.user_id = :uid
  1894. """
  1895. ),
  1896. {"uid": internal_uid},
  1897. )
  1898. await session.commit()
  1899. return {
  1900. "success": True,
  1901. "data": {"total_quantity": total_qty, "total_cost_energy": total_cost_energy},
  1902. }
  1903. except HTTPException:
  1904. raise
  1905. except Exception as exc: # noqa: BLE001
  1906. logger.exception("ChatBot 购物车购买失败: %s", exc)
  1907. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  1908. @app.post("/api/users/{user_id}/chatbot-shop-purchase")
  1909. async def purchase_chatbot_shop_item(
  1910. user_id: str,
  1911. request: ChatbotShopPurchaseRequest,
  1912. _: None = Depends(require_user_session),
  1913. ):
  1914. """使用对话能量石购买上架中的家具/幕布。"""
  1915. try:
  1916. async with db_manager.get_session() as session:
  1917. assets_user_id_expr = (
  1918. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  1919. if await _mysql_user_id_column_is_bigint(session, "user_assets")
  1920. else ":user_id"
  1921. )
  1922. item_res = await session.execute(
  1923. text(
  1924. """
  1925. SELECT
  1926. id,
  1927. price_energy,
  1928. price_crystal,
  1929. name,
  1930. image_name,
  1931. max_per_user,
  1932. repeat_purchase_mode,
  1933. is_active,
  1934. item_type
  1935. FROM shop_items
  1936. WHERE id = :item_id
  1937. LIMIT 1
  1938. """
  1939. ),
  1940. {"item_id": request.item_id},
  1941. )
  1942. item_row = item_res.mappings().first()
  1943. if not item_row or int(item_row.get("is_active") or 0) != 1:
  1944. raise HTTPException(status_code=404, detail={"code": SHOP_ITEM_NOT_FOUND})
  1945. if str(item_row.get("item_type") or "") not in ("furniture", "backdrop"):
  1946. raise HTTPException(status_code=404, detail={"code": SHOP_ITEM_NOT_FOUND})
  1947. owned_res = await session.execute(
  1948. text(
  1949. f"""
  1950. SELECT COALESCE(ua.owned_qty, 0) AS owned_qty
  1951. FROM shop_items si
  1952. LEFT JOIN user_assets ua
  1953. ON ua.item_id = si.id
  1954. AND ua.user_id = {assets_user_id_expr}
  1955. WHERE si.id = :item_id
  1956. LIMIT 1
  1957. """
  1958. ),
  1959. {"user_id": user_id, "item_id": request.item_id},
  1960. )
  1961. owned_row = owned_res.mappings().first()
  1962. owned_qty = int((owned_row or {}).get("owned_qty") or 0)
  1963. max_per = item_row.get("max_per_user")
  1964. max_per_int = int(max_per) if max_per is not None else None
  1965. if max_per_int is not None and owned_qty >= max_per_int:
  1966. raise HTTPException(status_code=400, detail={"code": PURCHASE_LIMIT_REACHED})
  1967. repeat_mode = str(item_row.get("repeat_purchase_mode") or "single")
  1968. if repeat_mode == "single" and owned_qty >= 1:
  1969. raise HTTPException(status_code=400, detail={"code": PURCHASE_LIMIT_REACHED})
  1970. cost = _floor_shop_price_energy(item_row.get("price_energy"))
  1971. bal_res = await session.execute(
  1972. text(
  1973. """
  1974. SELECT id, conversation_energy_stone_total
  1975. FROM users
  1976. WHERE user_id = :user_id
  1977. LIMIT 1
  1978. """
  1979. ),
  1980. {"user_id": user_id},
  1981. )
  1982. bal_row = bal_res.mappings().first()
  1983. if not bal_row:
  1984. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  1985. balance = int(bal_row.get("conversation_energy_stone_total") or 0)
  1986. if cost > balance:
  1987. raise HTTPException(
  1988. status_code=400,
  1989. detail={"code": INSUFFICIENT_CONVERSATION_ENERGY},
  1990. )
  1991. upd_res = await session.execute(
  1992. text(
  1993. """
  1994. UPDATE users
  1995. SET conversation_energy_stone_total = conversation_energy_stone_total - :cost
  1996. WHERE user_id = :user_id
  1997. AND conversation_energy_stone_total >= :cost
  1998. """
  1999. ),
  2000. {"cost": cost, "user_id": user_id},
  2001. )
  2002. if (getattr(upd_res, "rowcount", None) or 0) < 1:
  2003. raise HTTPException(
  2004. status_code=400,
  2005. detail={"code": INSUFFICIENT_CONVERSATION_ENERGY},
  2006. )
  2007. chk = await session.execute(
  2008. text(
  2009. f"""
  2010. SELECT id FROM user_assets
  2011. WHERE user_id = {assets_user_id_expr} AND item_id = :item_id
  2012. LIMIT 1
  2013. """
  2014. ),
  2015. {"user_id": user_id, "item_id": request.item_id},
  2016. )
  2017. existing_uaid = chk.scalar_one_or_none()
  2018. if existing_uaid is not None:
  2019. await session.execute(
  2020. text(
  2021. """
  2022. UPDATE user_assets
  2023. SET owned_qty = owned_qty + 1,
  2024. last_acquired_at = NOW(),
  2025. updated_at = NOW()
  2026. WHERE id = :id
  2027. """
  2028. ),
  2029. {"id": int(existing_uaid)},
  2030. )
  2031. else:
  2032. await session.execute(
  2033. text(
  2034. f"""
  2035. INSERT INTO user_assets
  2036. (user_id, item_id, owned_qty, used_qty, last_acquired_at, created_at, updated_at)
  2037. VALUES
  2038. ({assets_user_id_expr}, :item_id, 1, 0, NOW(), NOW(), NOW())
  2039. """
  2040. ),
  2041. {"user_id": user_id, "item_id": request.item_id},
  2042. )
  2043. internal_uid = int(bal_row["id"])
  2044. # 直购成功:购物车中若有同商品则减 1 件,避免与已购数量叠加超过上限
  2045. await session.execute(
  2046. text(
  2047. """
  2048. UPDATE shopping_cart_items sci
  2049. INNER JOIN shopping_carts sc ON sc.id = sci.cart_id
  2050. SET sci.quantity = sci.quantity - 1,
  2051. sci.updated_at = NOW()
  2052. WHERE sc.user_id = :uid
  2053. AND sci.item_id = :item_id
  2054. AND sci.quantity >= 1
  2055. """
  2056. ),
  2057. {"uid": internal_uid, "item_id": int(request.item_id)},
  2058. )
  2059. await session.execute(
  2060. text(
  2061. """
  2062. DELETE sci FROM shopping_cart_items sci
  2063. INNER JOIN shopping_carts sc ON sc.id = sci.cart_id
  2064. WHERE sc.user_id = :uid
  2065. AND sci.item_id = :item_id
  2066. AND sci.quantity = 0
  2067. """
  2068. ),
  2069. {"uid": internal_uid, "item_id": int(request.item_id)},
  2070. )
  2071. # 购买订单主表/明细(弹窗直购无购物车,cart_id 用 0 占位)
  2072. item_name_snap = str(item_row.get("name") or "")[:100]
  2073. image_name_snap = str(item_row.get("image_name") or "")[:255]
  2074. try:
  2075. pc_snap = item_row.get("price_crystal")
  2076. unit_pc = Decimal(str(pc_snap)) if pc_snap is not None else Decimal("0")
  2077. except (ArithmeticError, ValueError, TypeError):
  2078. unit_pc = Decimal("0")
  2079. unit_pe = Decimal(str(cost))
  2080. await session.execute(
  2081. text(
  2082. """
  2083. INSERT INTO purchase_orders
  2084. (user_id, cart_id, status, total_quantity, total_cost_energy, total_cost_crystal, completed_at)
  2085. VALUES
  2086. (:uid, 0, 'completed', 1, :tce, 0.00, NOW())
  2087. """
  2088. ),
  2089. {"uid": internal_uid, "tce": unit_pe},
  2090. )
  2091. oid_row = await session.execute(text("SELECT LAST_INSERT_ID() AS oid"))
  2092. order_id_raw = oid_row.scalar_one()
  2093. order_id = int(order_id_raw) if order_id_raw is not None else 0
  2094. if order_id <= 0:
  2095. raise RuntimeError("purchase_orders insert did not return id")
  2096. await session.execute(
  2097. text(
  2098. """
  2099. INSERT INTO purchase_order_items
  2100. (order_id, item_id, quantity, unit_price_energy, unit_price_crystal,
  2101. cost_energy, cost_crystal, item_name_snapshot, image_name_snapshot)
  2102. VALUES
  2103. (:order_id, :item_id, 1, :upe, :upc, :ce, 0.00, :name_snap, :img_snap)
  2104. """
  2105. ),
  2106. {
  2107. "order_id": order_id,
  2108. "item_id": int(request.item_id),
  2109. "upe": unit_pe,
  2110. "upc": unit_pc,
  2111. "ce": unit_pe,
  2112. "name_snap": item_name_snap,
  2113. "img_snap": image_name_snap,
  2114. },
  2115. )
  2116. await session.commit()
  2117. return {
  2118. "success": True,
  2119. "data": {
  2120. "item_id": int(request.item_id),
  2121. "cost_energy": cost,
  2122. "order_id": order_id,
  2123. },
  2124. }
  2125. except HTTPException:
  2126. raise
  2127. except Exception as exc: # noqa: BLE001
  2128. logger.exception("ChatBot 商店购买失败: %s", exc)
  2129. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  2130. @app.put("/api/users/{user_id}/chatbot-backdrop")
  2131. async def update_chatbot_backdrop(
  2132. user_id: str,
  2133. request: UpdateChatbotBackdropRequest,
  2134. _: None = Depends(require_user_session),
  2135. ):
  2136. """切换用户 ChatBot 当前幕布。"""
  2137. try:
  2138. async with db_manager.get_session() as session:
  2139. async def _get_user_id_is_bigint(table_name: str) -> bool:
  2140. res = await session.execute(
  2141. text(
  2142. """
  2143. SELECT DATA_TYPE
  2144. FROM information_schema.columns
  2145. WHERE table_schema = :db
  2146. AND table_name = :table
  2147. AND column_name = 'user_id'
  2148. """
  2149. ),
  2150. {"db": settings.MYSQL_DATABASE, "table": table_name},
  2151. )
  2152. row = res.mappings().first()
  2153. return "bigint" in str((row or {}).get("DATA_TYPE") or "").lower()
  2154. backdrop_user_id_expr = (
  2155. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  2156. if await _get_user_id_is_bigint("user_chatbot_backdrops")
  2157. else ":user_id"
  2158. )
  2159. placement_user_id_expr = (
  2160. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  2161. if await _get_user_id_is_bigint("user_chatbot_slot_placements")
  2162. else ":user_id"
  2163. )
  2164. assets_user_id_expr = (
  2165. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  2166. if await _get_user_id_is_bigint("user_assets")
  2167. else ":user_id"
  2168. )
  2169. owned_res = await session.execute(
  2170. text(
  2171. f"""
  2172. SELECT
  2173. ua.id AS user_asset_id,
  2174. si.id AS item_id,
  2175. si.item_type,
  2176. COALESCE(si.default_z_index, 0) AS default_z_index
  2177. FROM user_assets ua
  2178. JOIN shop_items si ON si.id = ua.item_id
  2179. WHERE ua.user_id = {assets_user_id_expr}
  2180. AND ua.item_id = :item_id
  2181. AND ua.owned_qty > 0
  2182. AND si.is_active = 1
  2183. LIMIT 1
  2184. """
  2185. ),
  2186. {"user_id": user_id, "item_id": request.backdrop_item_id},
  2187. )
  2188. owned_row = owned_res.mappings().first()
  2189. if not owned_row:
  2190. raise HTTPException(status_code=400, detail={"code": "ITEM_NOT_OWNED"})
  2191. if str(owned_row.get("item_type") or "") != "backdrop":
  2192. raise HTTPException(status_code=400, detail={"code": "ITEM_NOT_BACKDROP"})
  2193. target_backdrop_item_id = int(request.backdrop_item_id)
  2194. current_backdrop_res = await session.execute(
  2195. text(
  2196. f"""
  2197. SELECT backdrop_item_id
  2198. FROM user_chatbot_backdrops
  2199. WHERE user_id = {backdrop_user_id_expr}
  2200. ORDER BY updated_at DESC, id DESC
  2201. LIMIT 1
  2202. """
  2203. ),
  2204. {"user_id": user_id},
  2205. )
  2206. current_backdrop_row = current_backdrop_res.mappings().first()
  2207. source_backdrop_item_id = (
  2208. int(current_backdrop_row["backdrop_item_id"])
  2209. if current_backdrop_row and current_backdrop_row.get("backdrop_item_id") is not None
  2210. else None
  2211. )
  2212. await session.execute(
  2213. text(
  2214. f"""
  2215. DELETE FROM user_chatbot_backdrops
  2216. WHERE user_id = {backdrop_user_id_expr}
  2217. """
  2218. ),
  2219. {"user_id": user_id},
  2220. )
  2221. await session.execute(
  2222. text(
  2223. f"""
  2224. INSERT INTO user_chatbot_backdrops
  2225. (user_id, backdrop_item_id, z_index, created_at, updated_at)
  2226. VALUES
  2227. ({backdrop_user_id_expr}, :backdrop_item_id, :z_index, NOW(), NOW())
  2228. """
  2229. ),
  2230. {
  2231. "user_id": user_id,
  2232. "backdrop_item_id": target_backdrop_item_id,
  2233. "z_index": int(owned_row.get("default_z_index") or 0),
  2234. },
  2235. )
  2236. slot_table_exists_res = await session.execute(
  2237. text(
  2238. """
  2239. SELECT COUNT(*) AS c
  2240. FROM information_schema.tables
  2241. WHERE table_schema = :db
  2242. AND table_name = 'user_chatbot_slot_placements'
  2243. """
  2244. ),
  2245. {"db": settings.MYSQL_DATABASE},
  2246. )
  2247. slot_table_exists = int((slot_table_exists_res.mappings().first() or {}).get("c") or 0) > 0
  2248. # 幕布切换时:先清空目标幕布已有摆放,再尝试按槽位复制来源幕布的有效摆放。
  2249. if slot_table_exists:
  2250. await session.execute(
  2251. text(
  2252. f"""
  2253. DELETE FROM user_chatbot_slot_placements
  2254. WHERE user_id = {placement_user_id_expr}
  2255. AND backdrop_item_id = :target_backdrop_item_id
  2256. """
  2257. ),
  2258. {"user_id": user_id, "target_backdrop_item_id": target_backdrop_item_id},
  2259. )
  2260. if source_backdrop_item_id is not None and source_backdrop_item_id != target_backdrop_item_id:
  2261. await session.execute(
  2262. text(
  2263. f"""
  2264. INSERT INTO user_chatbot_slot_placements
  2265. (user_id, backdrop_item_id, slot_code, user_asset_id, item_id, z_index,
  2266. image_name_snapshot, placed_at, updated_at)
  2267. SELECT
  2268. src.user_id,
  2269. :target_backdrop_item_id AS backdrop_item_id,
  2270. src.slot_code,
  2271. src.user_asset_id,
  2272. src.item_id,
  2273. src.z_index,
  2274. src.image_name_snapshot,
  2275. NOW(),
  2276. NOW()
  2277. FROM user_chatbot_slot_placements src
  2278. JOIN chatbot_backdrop_slots target_slot
  2279. ON target_slot.backdrop_item_id = :target_backdrop_item_id
  2280. AND target_slot.slot_code = src.slot_code
  2281. AND target_slot.is_active = 1
  2282. WHERE src.user_id = {placement_user_id_expr}
  2283. AND src.backdrop_item_id = :source_backdrop_item_id
  2284. ON DUPLICATE KEY UPDATE
  2285. user_asset_id = VALUES(user_asset_id),
  2286. item_id = VALUES(item_id),
  2287. z_index = VALUES(z_index),
  2288. image_name_snapshot = VALUES(image_name_snapshot),
  2289. placed_at = VALUES(placed_at),
  2290. updated_at = NOW()
  2291. """
  2292. ),
  2293. {
  2294. "user_id": user_id,
  2295. "source_backdrop_item_id": source_backdrop_item_id,
  2296. "target_backdrop_item_id": target_backdrop_item_id,
  2297. },
  2298. )
  2299. await session.commit()
  2300. return {
  2301. "success": True,
  2302. "data": {"backdrop_item_id": target_backdrop_item_id},
  2303. }
  2304. except HTTPException:
  2305. raise
  2306. except Exception as exc: # noqa: BLE001
  2307. logger.exception("切换 ChatBot 幕布失败: %s", exc)
  2308. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  2309. @app.get("/api/users/{user_id}/chatbot-furniture/equip-preview")
  2310. async def get_chatbot_furniture_equip_preview(
  2311. user_id: str,
  2312. item_id: int = Query(..., ge=1),
  2313. _: None = Depends(require_user_session),
  2314. ):
  2315. """
  2316. 装备前预览:解析与 POST equip 相同的槽位规则,返回槽位几何与场景图文件名。
  2317. 无有效槽位或数据不全时 data 为 null(前端不展示预览即可)。
  2318. """
  2319. try:
  2320. async with db_manager.get_session() as session:
  2321. async def _get_user_id_is_bigint(table_name: str) -> bool:
  2322. res = await session.execute(
  2323. text(
  2324. """
  2325. SELECT DATA_TYPE
  2326. FROM information_schema.columns
  2327. WHERE table_schema = :db
  2328. AND table_name = :table
  2329. AND column_name = 'user_id'
  2330. """
  2331. ),
  2332. {"db": settings.MYSQL_DATABASE, "table": table_name},
  2333. )
  2334. row = res.mappings().first()
  2335. return "bigint" in str((row or {}).get("DATA_TYPE") or "").lower()
  2336. backdrop_user_id_expr = (
  2337. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  2338. if await _get_user_id_is_bigint("user_chatbot_backdrops")
  2339. else ":user_id"
  2340. )
  2341. item_res = await session.execute(
  2342. text(
  2343. """
  2344. SELECT
  2345. si.id AS item_id,
  2346. si.item_type,
  2347. si.image_name,
  2348. si.render_image_name,
  2349. COALESCE(si.default_z_index, 0) AS default_z_index
  2350. FROM shop_items si
  2351. WHERE si.id = :item_id
  2352. AND si.is_active = 1
  2353. LIMIT 1
  2354. """
  2355. ),
  2356. {"item_id": item_id},
  2357. )
  2358. item_row = item_res.mappings().first()
  2359. if not item_row or str(item_row.get("item_type") or "") != "furniture":
  2360. return {"success": True, "data": None}
  2361. rules_table_res = await session.execute(
  2362. text(
  2363. """
  2364. SELECT COUNT(*) AS c
  2365. FROM information_schema.tables
  2366. WHERE table_schema = :db
  2367. AND table_name = 'shop_item_slot_rules'
  2368. """
  2369. ),
  2370. {"db": settings.MYSQL_DATABASE},
  2371. )
  2372. if int((rules_table_res.mappings().first() or {}).get("c") or 0) == 0:
  2373. return {"success": True, "data": None}
  2374. current_backdrop_res = await session.execute(
  2375. text(
  2376. f"""
  2377. SELECT backdrop_item_id
  2378. FROM user_chatbot_backdrops
  2379. WHERE user_id = {backdrop_user_id_expr}
  2380. ORDER BY updated_at DESC, id DESC
  2381. LIMIT 1
  2382. """
  2383. ),
  2384. {"user_id": user_id},
  2385. )
  2386. current_backdrop_row = current_backdrop_res.mappings().first()
  2387. if not current_backdrop_row or current_backdrop_row.get("backdrop_item_id") is None:
  2388. return {"success": True, "data": None}
  2389. backdrop_item_id = int(current_backdrop_row["backdrop_item_id"])
  2390. target_slot_res = await session.execute(
  2391. text(
  2392. """
  2393. SELECT
  2394. r.slot_code,
  2395. r.id AS rule_id
  2396. FROM shop_item_slot_rules r
  2397. JOIN chatbot_backdrop_slots s
  2398. ON s.backdrop_item_id = r.backdrop_item_id
  2399. AND s.slot_code = r.slot_code
  2400. AND s.is_active = 1
  2401. WHERE r.item_id = :item_id
  2402. AND r.backdrop_item_id = :backdrop_item_id
  2403. AND r.is_active = 1
  2404. ORDER BY COALESCE(r.is_default, 0) DESC, COALESCE(r.priority, 9999) ASC, r.id ASC
  2405. LIMIT 1
  2406. """
  2407. ),
  2408. {"item_id": item_id, "backdrop_item_id": backdrop_item_id},
  2409. )
  2410. target_slot_row = target_slot_res.mappings().first()
  2411. if not target_slot_row or not target_slot_row.get("slot_code"):
  2412. return {"success": True, "data": None}
  2413. slot_code = str(target_slot_row["slot_code"])
  2414. slot_geo_res = await session.execute(
  2415. text(
  2416. """
  2417. SELECT
  2418. s.id,
  2419. s.slot_code,
  2420. s.placement_type,
  2421. s.start_row,
  2422. s.start_col,
  2423. s.size_rows,
  2424. s.size_cols,
  2425. COALESCE(s.z_index, 0) AS z_index,
  2426. s.render_mode,
  2427. s.offset_x,
  2428. s.offset_y,
  2429. s.pixel_width,
  2430. s.pixel_height
  2431. FROM chatbot_backdrop_slots s
  2432. WHERE s.backdrop_item_id = :backdrop_item_id
  2433. AND s.slot_code = :slot_code
  2434. AND s.is_active = 1
  2435. LIMIT 1
  2436. """
  2437. ),
  2438. {"backdrop_item_id": backdrop_item_id, "slot_code": slot_code},
  2439. )
  2440. slot_row = slot_geo_res.mappings().first()
  2441. if not slot_row:
  2442. return {"success": True, "data": None}
  2443. preview_image_name = scene_image_name_from_shop_row(dict(item_row))
  2444. item_z_index = int(item_row.get("default_z_index") or 0)
  2445. slot_payload = {
  2446. "id": int(slot_row["id"]),
  2447. "slot_code": str(slot_row.get("slot_code") or ""),
  2448. "placement_type": str(slot_row.get("placement_type") or "floor"),
  2449. "start_row": int(slot_row.get("start_row") or 1),
  2450. "start_col": int(slot_row.get("start_col") or 1),
  2451. "size_rows": int(slot_row.get("size_rows") or 1),
  2452. "size_cols": int(slot_row.get("size_cols") or 1),
  2453. # 与 POST /chatbot-furniture/equip 保持一致:渲染层级取商品 default_z_index
  2454. "z_index": item_z_index,
  2455. "render_mode": slot_row.get("render_mode"),
  2456. "offset_x": slot_row.get("offset_x"),
  2457. "offset_y": slot_row.get("offset_y"),
  2458. "pixel_width": slot_row.get("pixel_width"),
  2459. "pixel_height": slot_row.get("pixel_height"),
  2460. }
  2461. return {
  2462. "success": True,
  2463. "data": {
  2464. "slot": slot_payload,
  2465. "preview_image_name": preview_image_name,
  2466. },
  2467. }
  2468. except Exception as exc: # noqa: BLE001
  2469. logger.exception("获取家具装备预览失败: %s", exc)
  2470. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  2471. @app.post("/api/users/{user_id}/chatbot-furniture/equip")
  2472. async def equip_chatbot_furniture(
  2473. user_id: str,
  2474. request: ChatbotFurnitureActionRequest,
  2475. _: None = Depends(require_user_session),
  2476. ):
  2477. """装备家具:同槽位已有元素则替换,否则新增。"""
  2478. try:
  2479. async with db_manager.get_session() as session:
  2480. async def _get_user_id_is_bigint(table_name: str) -> bool:
  2481. res = await session.execute(
  2482. text(
  2483. """
  2484. SELECT DATA_TYPE
  2485. FROM information_schema.columns
  2486. WHERE table_schema = :db
  2487. AND table_name = :table
  2488. AND column_name = 'user_id'
  2489. """
  2490. ),
  2491. {"db": settings.MYSQL_DATABASE, "table": table_name},
  2492. )
  2493. row = res.mappings().first()
  2494. return "bigint" in str((row or {}).get("DATA_TYPE") or "").lower()
  2495. assets_user_id_expr = (
  2496. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  2497. if await _get_user_id_is_bigint("user_assets")
  2498. else ":user_id"
  2499. )
  2500. backdrop_user_id_expr = (
  2501. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  2502. if await _get_user_id_is_bigint("user_chatbot_backdrops")
  2503. else ":user_id"
  2504. )
  2505. placement_user_id_expr = (
  2506. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  2507. if await _get_user_id_is_bigint("user_chatbot_slot_placements")
  2508. else ":user_id"
  2509. )
  2510. owned_res = await session.execute(
  2511. text(
  2512. f"""
  2513. SELECT
  2514. ua.id AS user_asset_id,
  2515. si.id AS item_id,
  2516. si.item_type,
  2517. si.image_name,
  2518. si.render_image_name,
  2519. COALESCE(si.default_z_index, 0) AS default_z_index
  2520. FROM user_assets ua
  2521. JOIN shop_items si ON si.id = ua.item_id
  2522. WHERE ua.user_id = {assets_user_id_expr}
  2523. AND ua.item_id = :item_id
  2524. AND ua.owned_qty > 0
  2525. AND si.is_active = 1
  2526. LIMIT 1
  2527. """
  2528. ),
  2529. {"user_id": user_id, "item_id": request.item_id},
  2530. )
  2531. owned_row = owned_res.mappings().first()
  2532. if not owned_row:
  2533. raise HTTPException(status_code=400, detail={"code": "ITEM_NOT_OWNED"})
  2534. if str(owned_row.get("item_type") or "") != "furniture":
  2535. raise HTTPException(status_code=400, detail={"code": "ITEM_NOT_FURNITURE"})
  2536. current_backdrop_res = await session.execute(
  2537. text(
  2538. f"""
  2539. SELECT backdrop_item_id
  2540. FROM user_chatbot_backdrops
  2541. WHERE user_id = {backdrop_user_id_expr}
  2542. ORDER BY updated_at DESC, id DESC
  2543. LIMIT 1
  2544. """
  2545. ),
  2546. {"user_id": user_id},
  2547. )
  2548. current_backdrop_row = current_backdrop_res.mappings().first()
  2549. if not current_backdrop_row or current_backdrop_row.get("backdrop_item_id") is None:
  2550. raise HTTPException(status_code=400, detail={"code": "BACKDROP_NOT_SET"})
  2551. backdrop_item_id = int(current_backdrop_row["backdrop_item_id"])
  2552. target_slot_res = await session.execute(
  2553. text(
  2554. """
  2555. SELECT
  2556. r.slot_code,
  2557. r.id AS rule_id
  2558. FROM shop_item_slot_rules r
  2559. JOIN chatbot_backdrop_slots s
  2560. ON s.backdrop_item_id = r.backdrop_item_id
  2561. AND s.slot_code = r.slot_code
  2562. AND s.is_active = 1
  2563. WHERE r.item_id = :item_id
  2564. AND r.backdrop_item_id = :backdrop_item_id
  2565. AND r.is_active = 1
  2566. ORDER BY COALESCE(r.is_default, 0) DESC, COALESCE(r.priority, 9999) ASC, r.id ASC
  2567. LIMIT 1
  2568. """
  2569. ),
  2570. {"item_id": request.item_id, "backdrop_item_id": backdrop_item_id},
  2571. )
  2572. target_slot_row = target_slot_res.mappings().first()
  2573. if not target_slot_row or not target_slot_row.get("slot_code"):
  2574. raise HTTPException(status_code=400, detail={"code": "NO_VALID_SLOT_FOR_ITEM"})
  2575. slot_code = str(target_slot_row["slot_code"])
  2576. dependency_table_res = await session.execute(
  2577. text(
  2578. """
  2579. SELECT COUNT(*) AS c
  2580. FROM information_schema.tables
  2581. WHERE table_schema = :db
  2582. AND table_name = 'chatbot_slot_dependencies'
  2583. """
  2584. ),
  2585. {"db": settings.MYSQL_DATABASE},
  2586. )
  2587. has_dependency_table = int((dependency_table_res.mappings().first() or {}).get("c") or 0) > 0
  2588. if has_dependency_table:
  2589. user_lang_res = await session.execute(
  2590. select(User.preferred_language).where(User.user_id == user_id).limit(1)
  2591. )
  2592. preferred_language = user_lang_res.scalar_one_or_none()
  2593. is_zh = str(preferred_language or "zh").lower().startswith("zh")
  2594. dependency_res = await session.execute(
  2595. text(
  2596. """
  2597. SELECT
  2598. dep.requires_slot_code,
  2599. dep.requires_biz_type,
  2600. cur.slot_name_zh AS current_slot_name_zh,
  2601. cur.slot_name_en AS current_slot_name_en,
  2602. req.slot_name_zh AS requires_slot_name_zh,
  2603. req.slot_name_en AS requires_slot_name_en
  2604. FROM chatbot_slot_dependencies
  2605. dep
  2606. LEFT JOIN chatbot_backdrop_slots cur
  2607. ON cur.backdrop_item_id = dep.backdrop_item_id
  2608. AND cur.slot_code = dep.slot_code
  2609. LEFT JOIN chatbot_backdrop_slots req
  2610. ON req.backdrop_item_id = dep.backdrop_item_id
  2611. AND req.slot_code = dep.requires_slot_code
  2612. WHERE dep.backdrop_item_id = :backdrop_item_id
  2613. AND dep.slot_code = :slot_code
  2614. AND dep.is_active = 1
  2615. ORDER BY COALESCE(dep.priority, 9999) ASC, dep.id ASC
  2616. """
  2617. ),
  2618. {"backdrop_item_id": backdrop_item_id, "slot_code": slot_code},
  2619. )
  2620. dependency_rows = dependency_res.mappings().all()
  2621. for dep in dependency_rows:
  2622. requires_slot_code = str(dep.get("requires_slot_code") or "").strip()
  2623. requires_biz_type = dep.get("requires_biz_type")
  2624. if not requires_slot_code:
  2625. continue
  2626. required_placement_res = await session.execute(
  2627. text(
  2628. f"""
  2629. SELECT
  2630. usp.item_id,
  2631. si.biz_type
  2632. FROM user_chatbot_slot_placements usp
  2633. LEFT JOIN shop_items si ON si.id = usp.item_id
  2634. WHERE usp.user_id = {placement_user_id_expr}
  2635. AND usp.backdrop_item_id = :backdrop_item_id
  2636. AND usp.slot_code = :slot_code
  2637. LIMIT 1
  2638. """
  2639. ),
  2640. {
  2641. "user_id": user_id,
  2642. "backdrop_item_id": backdrop_item_id,
  2643. "slot_code": requires_slot_code,
  2644. },
  2645. )
  2646. required_placement = required_placement_res.mappings().first()
  2647. if not required_placement:
  2648. current_slot_name = (
  2649. str(dep.get("current_slot_name_zh") or slot_code)
  2650. if is_zh
  2651. else str(dep.get("current_slot_name_en") or slot_code)
  2652. )
  2653. requires_slot_name = (
  2654. str(dep.get("requires_slot_name_zh") or requires_slot_code)
  2655. if is_zh
  2656. else str(dep.get("requires_slot_name_en") or requires_slot_code)
  2657. )
  2658. detail_message = (
  2659. f"请先在「{requires_slot_name}」放置支撑家具后,再放置「{current_slot_name}」。"
  2660. if is_zh
  2661. else f"Please place a support item in \"{requires_slot_name}\" before placing items in \"{current_slot_name}\"."
  2662. )
  2663. raise HTTPException(
  2664. status_code=400,
  2665. detail={"code": "SLOT_DEPENDENCY_NOT_SATISFIED", "message": detail_message},
  2666. )
  2667. if requires_biz_type:
  2668. required_biz_type = str(required_placement.get("biz_type") or "")
  2669. if required_biz_type != str(requires_biz_type):
  2670. current_slot_name = (
  2671. str(dep.get("current_slot_name_zh") or slot_code)
  2672. if is_zh
  2673. else str(dep.get("current_slot_name_en") or slot_code)
  2674. )
  2675. requires_slot_name = (
  2676. str(dep.get("requires_slot_name_zh") or requires_slot_code)
  2677. if is_zh
  2678. else str(dep.get("requires_slot_name_en") or requires_slot_code)
  2679. )
  2680. required_type_name = (
  2681. "桌类家具"
  2682. if str(requires_biz_type) == "table_cabinet" and is_zh
  2683. else "table item"
  2684. if str(requires_biz_type) == "table_cabinet"
  2685. else str(requires_biz_type)
  2686. )
  2687. detail_message = (
  2688. f"请先在「{requires_slot_name}」放置{required_type_name}后,再放置「{current_slot_name}」。"
  2689. if is_zh
  2690. else f"Please place a {required_type_name} in \"{requires_slot_name}\" before placing items in \"{current_slot_name}\"."
  2691. )
  2692. raise HTTPException(
  2693. status_code=400,
  2694. detail={"code": "SLOT_DEPENDENCY_NOT_SATISFIED", "message": detail_message},
  2695. )
  2696. await session.execute(
  2697. text(
  2698. f"""
  2699. INSERT INTO user_chatbot_slot_placements
  2700. (user_id, backdrop_item_id, slot_code, user_asset_id, item_id, z_index, image_name_snapshot, placed_at, updated_at)
  2701. VALUES
  2702. ({placement_user_id_expr}, :backdrop_item_id, :slot_code, :user_asset_id, :item_id, :z_index, :image_name_snapshot, NOW(), NOW())
  2703. ON DUPLICATE KEY UPDATE
  2704. user_asset_id = VALUES(user_asset_id),
  2705. item_id = VALUES(item_id),
  2706. z_index = VALUES(z_index),
  2707. image_name_snapshot = VALUES(image_name_snapshot),
  2708. updated_at = NOW()
  2709. """
  2710. ),
  2711. {
  2712. "user_id": user_id,
  2713. "backdrop_item_id": backdrop_item_id,
  2714. "slot_code": slot_code,
  2715. "user_asset_id": int(owned_row.get("user_asset_id") or 0),
  2716. "item_id": int(request.item_id),
  2717. "z_index": int(owned_row.get("default_z_index") or 0),
  2718. "image_name_snapshot": scene_image_name_from_shop_row(owned_row),
  2719. },
  2720. )
  2721. await session.commit()
  2722. return {
  2723. "success": True,
  2724. "data": {
  2725. "item_id": int(request.item_id),
  2726. "slot_code": slot_code,
  2727. "backdrop_item_id": backdrop_item_id,
  2728. },
  2729. }
  2730. except HTTPException:
  2731. raise
  2732. except Exception as exc: # noqa: BLE001
  2733. logger.exception("装备 ChatBot 家具失败: %s", exc)
  2734. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  2735. @app.post("/api/users/{user_id}/chatbot-furniture/unequip")
  2736. async def unequip_chatbot_furniture(
  2737. user_id: str,
  2738. request: ChatbotFurnitureActionRequest,
  2739. _: None = Depends(require_user_session),
  2740. ):
  2741. """卸下家具:移除当前幕布下该 item 的槽位摆放记录。"""
  2742. try:
  2743. async with db_manager.get_session() as session:
  2744. async def _get_user_id_is_bigint(table_name: str) -> bool:
  2745. res = await session.execute(
  2746. text(
  2747. """
  2748. SELECT DATA_TYPE
  2749. FROM information_schema.columns
  2750. WHERE table_schema = :db
  2751. AND table_name = :table
  2752. AND column_name = 'user_id'
  2753. """
  2754. ),
  2755. {"db": settings.MYSQL_DATABASE, "table": table_name},
  2756. )
  2757. row = res.mappings().first()
  2758. return "bigint" in str((row or {}).get("DATA_TYPE") or "").lower()
  2759. assets_user_id_expr = (
  2760. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  2761. if await _get_user_id_is_bigint("user_assets")
  2762. else ":user_id"
  2763. )
  2764. backdrop_user_id_expr = (
  2765. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  2766. if await _get_user_id_is_bigint("user_chatbot_backdrops")
  2767. else ":user_id"
  2768. )
  2769. placement_user_id_expr = (
  2770. "(SELECT id FROM users WHERE user_id = :user_id LIMIT 1)"
  2771. if await _get_user_id_is_bigint("user_chatbot_slot_placements")
  2772. else ":user_id"
  2773. )
  2774. owned_res = await session.execute(
  2775. text(
  2776. f"""
  2777. SELECT
  2778. si.id AS item_id,
  2779. si.item_type
  2780. FROM user_assets ua
  2781. JOIN shop_items si ON si.id = ua.item_id
  2782. WHERE ua.user_id = {assets_user_id_expr}
  2783. AND ua.item_id = :item_id
  2784. AND ua.owned_qty > 0
  2785. AND si.is_active = 1
  2786. LIMIT 1
  2787. """
  2788. ),
  2789. {"user_id": user_id, "item_id": request.item_id},
  2790. )
  2791. owned_row = owned_res.mappings().first()
  2792. if not owned_row:
  2793. raise HTTPException(status_code=400, detail={"code": "ITEM_NOT_OWNED"})
  2794. if str(owned_row.get("item_type") or "") != "furniture":
  2795. raise HTTPException(status_code=400, detail={"code": "ITEM_NOT_FURNITURE"})
  2796. current_backdrop_res = await session.execute(
  2797. text(
  2798. f"""
  2799. SELECT backdrop_item_id
  2800. FROM user_chatbot_backdrops
  2801. WHERE user_id = {backdrop_user_id_expr}
  2802. ORDER BY updated_at DESC, id DESC
  2803. LIMIT 1
  2804. """
  2805. ),
  2806. {"user_id": user_id},
  2807. )
  2808. current_backdrop_row = current_backdrop_res.mappings().first()
  2809. if not current_backdrop_row or current_backdrop_row.get("backdrop_item_id") is None:
  2810. raise HTTPException(status_code=400, detail={"code": "BACKDROP_NOT_SET"})
  2811. backdrop_item_id = int(current_backdrop_row["backdrop_item_id"])
  2812. dependency_table_res = await session.execute(
  2813. text(
  2814. """
  2815. SELECT COUNT(*) AS c
  2816. FROM information_schema.tables
  2817. WHERE table_schema = :db
  2818. AND table_name = 'chatbot_slot_dependencies'
  2819. """
  2820. ),
  2821. {"db": settings.MYSQL_DATABASE},
  2822. )
  2823. has_dependency_table = int((dependency_table_res.mappings().first() or {}).get("c") or 0) > 0
  2824. user_lang_res = await session.execute(
  2825. select(User.preferred_language).where(User.user_id == user_id).limit(1)
  2826. )
  2827. preferred_language = user_lang_res.scalar_one_or_none()
  2828. is_zh = str(preferred_language or "zh").lower().startswith("zh")
  2829. cascade_removed_count = 0
  2830. cascade_removed_item_ids: list[int] = []
  2831. cascade_notice: Optional[str] = None
  2832. if has_dependency_table:
  2833. cascade_notice_meta_res = await session.execute(
  2834. text(
  2835. f"""
  2836. SELECT
  2837. dep.slot_code AS child_slot_code,
  2838. dep.requires_slot_code AS base_slot_code,
  2839. child_slot.slot_name_zh AS child_slot_name_zh,
  2840. child_slot.slot_name_en AS child_slot_name_en,
  2841. base_slot.slot_name_zh AS base_slot_name_zh,
  2842. base_slot.slot_name_en AS base_slot_name_en
  2843. FROM user_chatbot_slot_placements child
  2844. JOIN chatbot_slot_dependencies dep
  2845. ON dep.backdrop_item_id = child.backdrop_item_id
  2846. AND dep.slot_code = child.slot_code
  2847. AND dep.is_active = 1
  2848. JOIN user_chatbot_slot_placements base
  2849. ON base.user_id = child.user_id
  2850. AND base.backdrop_item_id = child.backdrop_item_id
  2851. AND base.slot_code = dep.requires_slot_code
  2852. LEFT JOIN chatbot_backdrop_slots child_slot
  2853. ON child_slot.backdrop_item_id = dep.backdrop_item_id
  2854. AND child_slot.slot_code = dep.slot_code
  2855. LEFT JOIN chatbot_backdrop_slots base_slot
  2856. ON base_slot.backdrop_item_id = dep.backdrop_item_id
  2857. AND base_slot.slot_code = dep.requires_slot_code
  2858. WHERE child.user_id = {placement_user_id_expr}
  2859. AND child.backdrop_item_id = :backdrop_item_id
  2860. AND base.item_id = :item_id
  2861. AND child.item_id <> :item_id
  2862. LIMIT 1
  2863. """
  2864. ),
  2865. {
  2866. "user_id": user_id,
  2867. "backdrop_item_id": backdrop_item_id,
  2868. "item_id": int(request.item_id),
  2869. },
  2870. )
  2871. cascade_notice_meta = cascade_notice_meta_res.mappings().first()
  2872. cascade_item_res = await session.execute(
  2873. text(
  2874. f"""
  2875. SELECT DISTINCT child.item_id
  2876. FROM user_chatbot_slot_placements child
  2877. JOIN chatbot_slot_dependencies dep
  2878. ON dep.backdrop_item_id = child.backdrop_item_id
  2879. AND dep.slot_code = child.slot_code
  2880. AND dep.is_active = 1
  2881. JOIN user_chatbot_slot_placements base
  2882. ON base.user_id = child.user_id
  2883. AND base.backdrop_item_id = child.backdrop_item_id
  2884. AND base.slot_code = dep.requires_slot_code
  2885. WHERE child.user_id = {placement_user_id_expr}
  2886. AND child.backdrop_item_id = :backdrop_item_id
  2887. AND base.item_id = :item_id
  2888. AND child.item_id <> :item_id
  2889. """
  2890. ),
  2891. {
  2892. "user_id": user_id,
  2893. "backdrop_item_id": backdrop_item_id,
  2894. "item_id": int(request.item_id),
  2895. },
  2896. )
  2897. cascade_removed_item_ids = [
  2898. int(row["item_id"])
  2899. for row in cascade_item_res.mappings().all()
  2900. if row.get("item_id") is not None
  2901. ]
  2902. cascade_delete_res = await session.execute(
  2903. text(
  2904. f"""
  2905. DELETE child
  2906. FROM user_chatbot_slot_placements child
  2907. JOIN chatbot_slot_dependencies dep
  2908. ON dep.backdrop_item_id = child.backdrop_item_id
  2909. AND dep.slot_code = child.slot_code
  2910. AND dep.is_active = 1
  2911. JOIN user_chatbot_slot_placements base
  2912. ON base.user_id = child.user_id
  2913. AND base.backdrop_item_id = child.backdrop_item_id
  2914. AND base.slot_code = dep.requires_slot_code
  2915. WHERE child.user_id = {placement_user_id_expr}
  2916. AND child.backdrop_item_id = :backdrop_item_id
  2917. AND base.item_id = :item_id
  2918. AND child.item_id <> :item_id
  2919. """
  2920. ),
  2921. {
  2922. "user_id": user_id,
  2923. "backdrop_item_id": backdrop_item_id,
  2924. "item_id": int(request.item_id),
  2925. },
  2926. )
  2927. cascade_removed_count = int(cascade_delete_res.rowcount or 0)
  2928. if cascade_removed_count > 0 and cascade_notice_meta:
  2929. base_name = (
  2930. str(cascade_notice_meta.get("base_slot_name_zh") or cascade_notice_meta.get("base_slot_code") or "")
  2931. if is_zh
  2932. else str(cascade_notice_meta.get("base_slot_name_en") or cascade_notice_meta.get("base_slot_code") or "")
  2933. )
  2934. child_name = (
  2935. str(cascade_notice_meta.get("child_slot_name_zh") or cascade_notice_meta.get("child_slot_code") or "")
  2936. if is_zh
  2937. else str(cascade_notice_meta.get("child_slot_name_en") or cascade_notice_meta.get("child_slot_code") or "")
  2938. )
  2939. cascade_notice = (
  2940. f"你卸下了「{base_name}」的支撑家具,「{child_name}」上的关联物品已自动卸下。"
  2941. if is_zh
  2942. else f"You removed the support item in \"{base_name}\", so linked items in \"{child_name}\" were auto-unequipped."
  2943. )
  2944. delete_res = await session.execute(
  2945. text(
  2946. f"""
  2947. DELETE FROM user_chatbot_slot_placements
  2948. WHERE user_id = {placement_user_id_expr}
  2949. AND backdrop_item_id = :backdrop_item_id
  2950. AND item_id = :item_id
  2951. """
  2952. ),
  2953. {
  2954. "user_id": user_id,
  2955. "backdrop_item_id": backdrop_item_id,
  2956. "item_id": int(request.item_id),
  2957. },
  2958. )
  2959. removed_count = int(delete_res.rowcount or 0)
  2960. await session.commit()
  2961. return {
  2962. "success": True,
  2963. "data": {
  2964. "item_id": int(request.item_id),
  2965. "removed_count": removed_count,
  2966. "backdrop_item_id": backdrop_item_id,
  2967. "cascade_removed_count": cascade_removed_count,
  2968. "cascade_removed_item_ids": cascade_removed_item_ids,
  2969. "cascade_notice": cascade_notice,
  2970. },
  2971. }
  2972. except HTTPException:
  2973. raise
  2974. except Exception as exc: # noqa: BLE001
  2975. logger.exception("卸下 ChatBot 家具失败: %s", exc)
  2976. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  2977. @app.post("/api/users/{user_id}/claim-share-reward")
  2978. async def claim_share_reward(user_id: str, _: None = Depends(require_user_session)):
  2979. """
  2980. 领取分享奖励
  2981. - 给用户添加新年背景图片(happynewyear)
  2982. - 设置用户的当前背景图片为新年的背景
  2983. Args:
  2984. user_id: 用户ID
  2985. Returns:
  2986. {
  2987. "success": true,
  2988. "data": {
  2989. "user_id": "xxx",
  2990. "background_image_id": "happynewyear",
  2991. "message": "分享奖励已领取"
  2992. }
  2993. }
  2994. """
  2995. try:
  2996. from database import db_manager
  2997. from models_db import User, UserBackgroundImage
  2998. from sqlalchemy import select, update
  2999. async with db_manager.get_session() as session:
  3000. # 1. 检查用户是否存在
  3001. result = await session.execute(
  3002. select(User).where(User.user_id == user_id)
  3003. )
  3004. user = result.scalar_one_or_none()
  3005. if not user:
  3006. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  3007. # 2. 检查用户是否已经拥有新年背景
  3008. bg_result = await session.execute(
  3009. select(UserBackgroundImage).where(
  3010. UserBackgroundImage.user_id == user_id,
  3011. UserBackgroundImage.image_id == "happynewyear"
  3012. )
  3013. )
  3014. existing_bg = bg_result.scalar_one_or_none()
  3015. # 3. 如果还没有,添加到用户背景图片列表
  3016. if not existing_bg:
  3017. user_bg_image = UserBackgroundImage(
  3018. user_id=user_id,
  3019. image_id="happynewyear",
  3020. obtained_type="gift",
  3021. obtained_source="share_reward"
  3022. )
  3023. session.add(user_bg_image)
  3024. logger.info(f"✅ 为用户添加新年背景图片: user_id={user_id}")
  3025. else:
  3026. logger.info(f"⏭️ 用户已拥有新年背景图片: user_id={user_id}")
  3027. # 4. 更新用户的当前背景图片
  3028. await session.execute(
  3029. update(User)
  3030. .where(User.user_id == user_id)
  3031. .values(current_background_image_id="happynewyear")
  3032. )
  3033. # 5. 更新用户的 has_shared_avatar 状态
  3034. from models_db import UserUIState
  3035. ui_state_result = await session.execute(
  3036. select(UserUIState).where(UserUIState.user_id == user_id)
  3037. )
  3038. ui_state = ui_state_result.scalar_one_or_none()
  3039. if ui_state:
  3040. ui_state.has_shared_avatar = True
  3041. session.add(ui_state)
  3042. logger.info(f"✅ 更新用户分享头像状态: user_id={user_id}, has_shared_avatar=True")
  3043. else:
  3044. # 如果不存在 UI 状态记录,创建一个新的
  3045. new_ui_state = UserUIState(
  3046. user_id=user_id,
  3047. has_shared_avatar=True
  3048. )
  3049. session.add(new_ui_state)
  3050. logger.info(f"✅ 创建用户UI状态并设置分享头像状态: user_id={user_id}, has_shared_avatar=True")
  3051. # 6. 获取背景图片的 metadata(用于前端设置透明度等)
  3052. bg_metadata = None
  3053. try:
  3054. from models_db import BackgroundImage
  3055. bg_info_result = await session.execute(
  3056. select(BackgroundImage).where(BackgroundImage.image_id == "happynewyear")
  3057. )
  3058. bg_info = bg_info_result.scalar_one_or_none()
  3059. if bg_info and bg_info.metadata_json:
  3060. bg_metadata = bg_info.metadata_json
  3061. except Exception as e:
  3062. logger.warning(f"⚠️ 获取背景图片metadata失败: {e}")
  3063. await session.commit()
  3064. logger.info(f"✅ 用户领取分享奖励成功: user_id={user_id}, background_image_id=happynewyear")
  3065. return {
  3066. "success": True,
  3067. "data": {
  3068. "user_id": user_id,
  3069. "background_image_id": "happynewyear",
  3070. "background_image_metadata": bg_metadata,
  3071. "message": "分享奖励已领取"
  3072. }
  3073. }
  3074. except HTTPException:
  3075. raise
  3076. except Exception as e:
  3077. logger.exception("领取分享奖励失败")
  3078. raise HTTPException(status_code=500, detail={"code": CLAIM_SHARE_REWARD_FAILED})
  3079. @app.get("/api/avatar-gifs")
  3080. async def get_avatar_gifs() -> Dict[str, Any]:
  3081. """
  3082. 获取头像 GIF 配置
  3083. - 优先读取数据库 avatar_assets 表(按 avatar_id、state 分组)
  3084. - 字段:avatar_id, state, image_url
  3085. - 失败/无数据时返回静态兜底配置
  3086. """
  3087. try:
  3088. from database import db_manager
  3089. async with db_manager.get_session() as session:
  3090. result = await session.execute(
  3091. text(
  3092. """
  3093. SELECT avatar_id, state, image_url
  3094. FROM avatar_assets
  3095. WHERE state IN ('default', 'positive', 'negative', 'talking')
  3096. ORDER BY avatar_id, state
  3097. """
  3098. )
  3099. )
  3100. rows = result.mappings().all()
  3101. if rows:
  3102. # 按 avatar_id 分组,转换为期望的格式
  3103. data: Dict[str, Dict[str, str]] = {}
  3104. for row in rows:
  3105. avatar_id = row.get("avatar_id")
  3106. state = row.get("state")
  3107. image_url = row.get("image_url")
  3108. if not avatar_id or not state or not image_url:
  3109. continue
  3110. if avatar_id not in data:
  3111. data[avatar_id] = {}
  3112. data[avatar_id][state] = image_url
  3113. if data:
  3114. return {"success": True, "data": data}
  3115. logger.warning("avatar_assets 表无记录,返回兜底静态配置")
  3116. except Exception as exc:
  3117. logger.error(f"获取头像 GIF 配置失败,使用兜底: {exc}")
  3118. return {"success": True, "data": {k: v.model_dump() for k, v in AVATAR_GIF_CONFIG.items()}}
  3119. @app.get("/api/share-images")
  3120. async def get_share_images() -> Dict[str, Any]:
  3121. """
  3122. 获取分享图片列表
  3123. - 优先从数据库 share_images 表读取(is_active=1,按 sort_order、id 排序)
  3124. - 失败或无数据时返回兜底静态列表
  3125. """
  3126. try:
  3127. from database import db_manager
  3128. async with db_manager.get_session() as session:
  3129. result = await session.execute(
  3130. text(
  3131. """
  3132. SELECT id, code, url, title, sort_order, is_active
  3133. FROM share_images
  3134. WHERE is_active = 1
  3135. ORDER BY sort_order ASC, id ASC
  3136. """
  3137. )
  3138. )
  3139. rows = result.mappings().all()
  3140. if rows:
  3141. data = [
  3142. {
  3143. "id": str(row.get("code") or row.get("id")),
  3144. "url": row.get("url"),
  3145. "title": row.get("title"),
  3146. "sort_order": row.get("sort_order"),
  3147. "is_active": bool(row.get("is_active")) if row.get("is_active") is not None else None,
  3148. }
  3149. for row in rows
  3150. ]
  3151. return {"success": True, "data": data}
  3152. logger.warning("share_images 表无记录,返回兜底静态列表")
  3153. except Exception as exc:
  3154. logger.error(f"获取分享图片失败,使用兜底: {exc}")
  3155. return {"success": True, "data": [item.model_dump() for item in SHARE_IMAGES]}
  3156. @app.put("/api/users/{user_id}/username")
  3157. async def update_username(user_id: str, request: UpdateUsernameRequest, _: None = Depends(require_user_session)):
  3158. """
  3159. 更新用户名
  3160. Args:
  3161. user_id: 用户ID
  3162. request: 更新请求(包含username)
  3163. Returns:
  3164. {
  3165. "success": true,
  3166. "message": "更新成功"
  3167. }
  3168. """
  3169. try:
  3170. success = await user_service.update_username(user_id, request.username)
  3171. if success:
  3172. return {
  3173. "success": True,
  3174. "message": "用户名更新成功"
  3175. }
  3176. else:
  3177. raise HTTPException(status_code=500, detail={"code": UPDATE_USERNAME_FAILED})
  3178. except HTTPException:
  3179. raise
  3180. except Exception as e:
  3181. logger.exception("更新用户名失败")
  3182. raise HTTPException(status_code=500, detail={"code": UPDATE_USERNAME_FAILED})
  3183. @app.put("/api/users/{user_id}/background-image-id")
  3184. async def update_background_image_id(user_id: str, request: UpdateBackgroundImageIdRequest, _: None = Depends(require_user_session)):
  3185. """
  3186. 更新用户当前使用的背景图片ID
  3187. Args:
  3188. user_id: 用户ID
  3189. request: 更新请求(包含background_image_id)
  3190. Returns:
  3191. {
  3192. "success": true,
  3193. "message": "更新成功"
  3194. }
  3195. """
  3196. try:
  3197. success = await user_service.update_current_background_image_id(
  3198. user_id, request.background_image_id
  3199. )
  3200. if not success:
  3201. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND_OR_UPDATE_FAILED})
  3202. return {"success": True, "message": "更新成功"}
  3203. except HTTPException:
  3204. raise
  3205. except Exception as e:
  3206. logger.exception("更新背景图片ID失败")
  3207. raise HTTPException(status_code=500, detail={"code": UPDATE_BG_IMAGE_FAILED}) from e
  3208. @app.put("/api/users/{user_id}/bot-name")
  3209. async def update_bot_name(user_id: str, request: UpdateBotNameRequest, _: None = Depends(require_user_session)):
  3210. """
  3211. 更新用户给机器人取的名字
  3212. Args:
  3213. user_id: 用户ID
  3214. request: 更新请求(包含bot_name)
  3215. Returns:
  3216. {
  3217. "success": true,
  3218. "message": "更新成功"
  3219. }
  3220. """
  3221. import asyncio
  3222. import time
  3223. start_time = time.time()
  3224. try:
  3225. # 🔥 添加超时保护(5秒),避免长时间等待
  3226. success = await asyncio.wait_for(
  3227. user_service.update_bot_name(user_id, request.bot_name),
  3228. timeout=5.0
  3229. )
  3230. duration = (time.time() - start_time) * 1000
  3231. if success:
  3232. return {
  3233. "success": True,
  3234. "message": "机器人名字更新成功"
  3235. }
  3236. else:
  3237. raise HTTPException(status_code=500, detail={"code": UPDATE_BOT_NAME_FAILED})
  3238. except asyncio.TimeoutError:
  3239. duration = (time.time() - start_time) * 1000
  3240. logger.error(f"更新机器人名字超时: user_id={user_id}, 耗时={duration:.1f}ms")
  3241. raise HTTPException(status_code=504, detail={"code": UPDATE_BOT_NAME_TIMEOUT})
  3242. except HTTPException:
  3243. raise
  3244. except Exception as e:
  3245. logger.exception("更新机器人名字异常")
  3246. raise HTTPException(status_code=500, detail={"code": UPDATE_BOT_NAME_FAILED})
  3247. @app.put("/api/users/{user_id}/preferred-language")
  3248. async def update_preferred_language(
  3249. user_id: str,
  3250. request: UpdatePreferredLanguageRequest,
  3251. _: None = Depends(require_user_session),
  3252. ):
  3253. """更新用户首选界面语言(写入 users.preferred_language)"""
  3254. try:
  3255. ok = await user_service.update_preferred_language(user_id, request.preferred_language)
  3256. if not ok:
  3257. raise HTTPException(status_code=500, detail={"code": UPDATE_PREFERRED_LANGUAGE_FAILED})
  3258. return {"success": True, "message": "语言偏好已更新"}
  3259. except HTTPException:
  3260. raise
  3261. except Exception:
  3262. logger.exception("更新首选语言失败")
  3263. raise HTTPException(status_code=500, detail={"code": UPDATE_PREFERRED_LANGUAGE_FAILED})
  3264. class SubmitFeedbackRequest(BaseModel):
  3265. """提交反馈请求"""
  3266. content: str
  3267. @app.post("/api/users/{user_id}/feedback")
  3268. async def submit_feedback(user_id: str, request: SubmitFeedbackRequest, _: None = Depends(require_user_session)):
  3269. """
  3270. 提交用户反馈
  3271. Args:
  3272. user_id: 用户ID
  3273. request: 反馈请求(包含content)
  3274. Returns:
  3275. {
  3276. "success": true,
  3277. "data": {
  3278. "feedback_id": "uuid",
  3279. "user_id": "uuid",
  3280. "content": "反馈内容",
  3281. "status": "pending",
  3282. "created_at": "2024-01-01T00:00:00"
  3283. }
  3284. }
  3285. """
  3286. try:
  3287. # 验证反馈内容
  3288. if not request.content or not request.content.strip():
  3289. raise HTTPException(status_code=400, detail={"code": FEEDBACK_CONTENT_EMPTY})
  3290. # 验证用户是否存在
  3291. async with db_manager.get_session() as session:
  3292. from models_db import User
  3293. user_result = await session.execute(
  3294. select(User).where(User.user_id == user_id)
  3295. )
  3296. user = user_result.scalar_one_or_none()
  3297. if not user:
  3298. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND})
  3299. # 创建反馈记录
  3300. feedback_id = str(uuid.uuid4())
  3301. feedback = Feedback(
  3302. feedback_id=feedback_id,
  3303. user_id=user_id,
  3304. content=request.content.strip(),
  3305. status="pending"
  3306. )
  3307. session.add(feedback)
  3308. await session.commit()
  3309. await session.refresh(feedback)
  3310. logger.info(f"✅ 用户反馈提交成功: user_id={user_id}, feedback_id={feedback_id}")
  3311. return {
  3312. "success": True,
  3313. "data": feedback.to_dict()
  3314. }
  3315. except HTTPException:
  3316. raise
  3317. except Exception as e:
  3318. logger.exception("提交反馈失败")
  3319. raise HTTPException(status_code=500, detail={"code": SUBMIT_FEEDBACK_FAILED})
  3320. @app.post("/api/auth/register/phone")
  3321. async def register_with_phone(request: RegisterPhoneRequest):
  3322. """
  3323. 手机号注册
  3324. Returns:
  3325. {
  3326. "success": true,
  3327. "data": {
  3328. "user_id": "uuid",
  3329. "username": "",
  3330. "phone": "",
  3331. "user_type": "registered",
  3332. "token": "会话token",
  3333. "expires_at": "过期时间",
  3334. ...
  3335. }
  3336. }
  3337. """
  3338. try:
  3339. user = await user_service.register_with_phone(
  3340. area_code=request.area_code,
  3341. phone=request.phone,
  3342. username=request.username,
  3343. user_id=request.user_id,
  3344. preferred_language=request.preferred_language,
  3345. )
  3346. # 生成会话 token(注册成功后自动登录)
  3347. session_data = await _generate_session_token(user["user_id"])
  3348. # 将 token 添加到返回数据中
  3349. user.update(session_data)
  3350. return {
  3351. "success": True,
  3352. "data": user
  3353. }
  3354. except AuthError as e:
  3355. raise HTTPException(status_code=400, detail={"code": e.code})
  3356. except Exception as e:
  3357. logger.exception("手机号注册失败")
  3358. raise HTTPException(status_code=500, detail={"code": REGISTER_FAILED})
  3359. @app.post("/api/auth/register/email")
  3360. async def register_with_email(request: RegisterEmailRequest):
  3361. """
  3362. 邮箱注册
  3363. Returns:
  3364. {
  3365. "success": true,
  3366. "data": {
  3367. "user_id": "uuid",
  3368. "username": "",
  3369. "email": "",
  3370. "user_type": "registered",
  3371. "token": "会话token",
  3372. "expires_at": "过期时间",
  3373. ...
  3374. }
  3375. }
  3376. """
  3377. try:
  3378. user = await user_service.register_with_email(
  3379. email=request.email,
  3380. username=request.username,
  3381. user_id=request.user_id,
  3382. preferred_language=request.preferred_language,
  3383. )
  3384. # 生成会话 token(注册成功后自动登录)
  3385. session_data = await _generate_session_token(user["user_id"])
  3386. # 将 token 添加到返回数据中
  3387. user.update(session_data)
  3388. return {
  3389. "success": True,
  3390. "data": user
  3391. }
  3392. except AuthError as e:
  3393. raise HTTPException(status_code=400, detail={"code": e.code})
  3394. except Exception as e:
  3395. logger.exception("邮箱注册失败")
  3396. raise HTTPException(status_code=500, detail={"code": REGISTER_FAILED})
  3397. @app.post("/api/auth/login/wechat")
  3398. async def login_with_wechat(request: LoginWechatRequest):
  3399. """
  3400. 微信登录/注册
  3401. Returns:
  3402. {
  3403. "success": true,
  3404. "data": {
  3405. "user_id": "uuid",
  3406. "username": "",
  3407. "wechat_openid": "",
  3408. "user_type": "registered",
  3409. "token": "会话token",
  3410. "expires_at": "过期时间",
  3411. ...
  3412. }
  3413. }
  3414. """
  3415. try:
  3416. user = await user_service.login_with_wechat(
  3417. openid=request.openid,
  3418. username=request.username
  3419. )
  3420. # 生成会话 token
  3421. session_data = await _generate_session_token(user["user_id"])
  3422. # 将 token 添加到返回数据中
  3423. user.update(session_data)
  3424. return {
  3425. "success": True,
  3426. "data": user
  3427. }
  3428. except Exception as e:
  3429. logger.exception("微信登录失败")
  3430. raise HTTPException(status_code=500, detail={"code": LOGIN_FAILED})
  3431. @app.post("/api/auth/login/qq")
  3432. async def login_with_qq(request: LoginQQRequest):
  3433. """
  3434. QQ登录/注册
  3435. Returns:
  3436. {
  3437. "success": true,
  3438. "data": {
  3439. "user_id": "uuid",
  3440. "username": "",
  3441. "qq_openid": "",
  3442. "user_type": "registered",
  3443. "token": "会话token",
  3444. "expires_at": "过期时间",
  3445. ...
  3446. }
  3447. }
  3448. """
  3449. try:
  3450. user = await user_service.login_with_qq(
  3451. openid=request.openid,
  3452. username=request.username
  3453. )
  3454. # 生成会话 token
  3455. session_data = await _generate_session_token(user["user_id"])
  3456. # 将 token 添加到返回数据中
  3457. user.update(session_data)
  3458. return {
  3459. "success": True,
  3460. "data": user
  3461. }
  3462. except Exception as e:
  3463. logger.exception("QQ登录失败")
  3464. raise HTTPException(status_code=500, detail={"code": LOGIN_FAILED})
  3465. @app.post("/api/auth/login/phone")
  3466. async def login_with_phone(request: LoginPhoneRequest):
  3467. """
  3468. 手机号登录
  3469. Returns:
  3470. {
  3471. "success": true,
  3472. "data": {
  3473. "user_id": "uuid",
  3474. "phone": "",
  3475. "token": "会话token",
  3476. "expires_at": "过期时间",
  3477. ...
  3478. }
  3479. }
  3480. """
  3481. try:
  3482. user = await user_service.login_with_phone(
  3483. phone=request.phone,
  3484. area_code=request.area_code,
  3485. preferred_language=request.preferred_language,
  3486. )
  3487. if user:
  3488. # 生成会话 token
  3489. session_data = await _generate_session_token(user["user_id"])
  3490. # 将 token 添加到返回数据中
  3491. user.update(session_data)
  3492. return {
  3493. "success": True,
  3494. "data": user
  3495. }
  3496. else:
  3497. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND_REGISTER_FIRST})
  3498. except HTTPException:
  3499. raise
  3500. except Exception as e:
  3501. logger.exception("手机号登录失败")
  3502. raise HTTPException(status_code=500, detail={"code": LOGIN_FAILED})
  3503. @app.post("/api/auth/login/email")
  3504. async def login_with_email(request: LoginEmailRequest):
  3505. """
  3506. 邮箱登录
  3507. Returns:
  3508. {
  3509. "success": true,
  3510. "data": {
  3511. "user_id": "uuid",
  3512. "email": "",
  3513. "token": "会话token",
  3514. "expires_at": "过期时间",
  3515. ...
  3516. }
  3517. }
  3518. """
  3519. try:
  3520. user = await user_service.login_with_email(
  3521. request.email,
  3522. preferred_language=request.preferred_language,
  3523. )
  3524. if user:
  3525. # 生成会话 token
  3526. session_data = await _generate_session_token(user["user_id"])
  3527. # 将 token 添加到返回数据中
  3528. user.update(session_data)
  3529. return {
  3530. "success": True,
  3531. "data": user
  3532. }
  3533. else:
  3534. raise HTTPException(status_code=404, detail={"code": USER_NOT_FOUND_REGISTER_FIRST})
  3535. except HTTPException:
  3536. raise
  3537. except Exception as e:
  3538. logger.exception("邮箱登录失败")
  3539. raise HTTPException(status_code=500, detail={"code": LOGIN_FAILED})
  3540. @app.post("/api/auth/email-continue")
  3541. async def email_continue(request: EmailContinueRequest):
  3542. """
  3543. 邮箱登录页 Continue:
  3544. - A/B 特殊用户:免验证码直接登录/首次注册
  3545. - 其他用户:发送验证码,前端跳转验证码输入页
  3546. """
  3547. try:
  3548. if await user_service.is_special_ab_email(request.email):
  3549. user, is_new_user = await user_service.auth_special_email_without_code(
  3550. request.email,
  3551. preferred_language=request.preferred_language,
  3552. )
  3553. session_data = await _generate_session_token(user["user_id"])
  3554. user.update(session_data)
  3555. user["is_new_user"] = is_new_user
  3556. if request.opted_out is not None:
  3557. try:
  3558. await user_service.upsert_community_choice(user["user_id"], request.opted_out)
  3559. except Exception:
  3560. logger.warning("特殊用户登录:同步 community_choice 失败", exc_info=True)
  3561. return {
  3562. "success": True,
  3563. "data": {
  3564. "requires_verification": False,
  3565. **user,
  3566. },
  3567. }
  3568. send_resp = await send_code(
  3569. SendCodeRequest(email=request.email, send_type="email"),
  3570. )
  3571. return {
  3572. "success": True,
  3573. "data": {
  3574. "requires_verification": True,
  3575. "code_id": send_resp["data"]["code_id"],
  3576. "message": send_resp["data"]["message"],
  3577. },
  3578. }
  3579. except AuthError as e:
  3580. raise HTTPException(status_code=400, detail={"code": e.code})
  3581. except HTTPException:
  3582. raise
  3583. except Exception:
  3584. logger.exception("email-continue 失败")
  3585. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  3586. @app.post("/api/auth/send-code")
  3587. async def send_code(request: SendCodeRequest):
  3588. """
  3589. 生成并保存验证码
  3590. 当用户点击 send code 按钮时调用此接口,生成临时验证码并保存到数据库
  3591. Args:
  3592. request: 发送验证码请求
  3593. - phone: 手机号(发送类型为短信时必填)
  3594. - email: 邮箱(发送类型为邮箱时必填)
  3595. - send_type: 发送类型 ("domestic_sms", "international_sms", "email")
  3596. Returns:
  3597. {
  3598. "success": true,
  3599. "data": {
  3600. "code_id": "验证码ID",
  3601. "message": "验证码已生成,等待发送"
  3602. }
  3603. }
  3604. """
  3605. try:
  3606. # 验证参数
  3607. if request.send_type in ["domestic_sms", "international_sms"]:
  3608. if not request.phone:
  3609. raise HTTPException(status_code=400, detail={"code": PHONE_REQUIRED})
  3610. elif request.send_type == "email":
  3611. if not request.email:
  3612. raise HTTPException(status_code=400, detail={"code": EMAIL_REQUIRED})
  3613. else:
  3614. raise HTTPException(status_code=400, detail={"code": SEND_TYPE_INVALID})
  3615. # 生成4位数字验证码
  3616. code = str(random.randint(1000, 9999))
  3617. code_id = str(uuid.uuid4())
  3618. # 保存到数据库
  3619. async with db_manager.get_session() as session:
  3620. # 🔥 将同一手机号/邮箱的旧验证码标记为无效
  3621. # 确保同一时间只有一个有效的验证码
  3622. if request.send_type in ["domestic_sms", "international_sms"]:
  3623. # 将同一手机号的旧验证码标记为无效
  3624. await session.execute(
  3625. update(VerificationCode)
  3626. .where(
  3627. VerificationCode.phone == request.phone,
  3628. VerificationCode.send_type == request.send_type,
  3629. VerificationCode.is_valid == True
  3630. )
  3631. .values(is_valid=False)
  3632. )
  3633. elif request.send_type == "email":
  3634. # 将同一邮箱的旧验证码标记为无效
  3635. await session.execute(
  3636. update(VerificationCode)
  3637. .where(
  3638. VerificationCode.email == request.email,
  3639. VerificationCode.send_type == request.send_type,
  3640. VerificationCode.is_valid == True
  3641. )
  3642. .values(is_valid=False)
  3643. )
  3644. # 创建新的验证码
  3645. verification_code = VerificationCode(
  3646. code_id=code_id,
  3647. area_code=request.area_code,
  3648. phone=request.phone,
  3649. email=request.email,
  3650. code=code,
  3651. send_type=request.send_type,
  3652. is_sent=False,
  3653. is_valid=True,
  3654. )
  3655. session.add(verification_code)
  3656. await session.commit()
  3657. logger.info(f"✅ 验证码已生成: code_id={code_id}, send_type={request.send_type}, area_code={request.area_code}, phone={request.phone}, email={request.email}")
  3658. return {
  3659. "success": True,
  3660. "data": {
  3661. "code_id": code_id,
  3662. "message": "验证码已生成,等待发送"
  3663. }
  3664. }
  3665. except HTTPException:
  3666. raise
  3667. except Exception as e:
  3668. logger.exception("生成验证码失败")
  3669. raise HTTPException(status_code=500, detail={"code": SEND_CODE_FAILED})
  3670. @app.post("/api/auth/verify-code")
  3671. async def verify_code(request: VerifyCodeRequest):
  3672. """
  3673. 验证验证码
  3674. Args:
  3675. request: 验证验证码请求
  3676. - phone: 手机号(发送类型为短信时必填)
  3677. - email: 邮箱(发送类型为邮箱时必填)
  3678. - code: 验证码
  3679. - send_type: 发送类型 ("domestic_sms", "international_sms", "email")
  3680. Returns:
  3681. {
  3682. "success": true,
  3683. "data": {
  3684. "valid": true/false,
  3685. "message": "验证成功" 或 "验证码错误"
  3686. }
  3687. }
  3688. """
  3689. try:
  3690. # 验证参数
  3691. if request.send_type in ["domestic_sms", "international_sms"]:
  3692. if not request.phone:
  3693. raise HTTPException(status_code=400, detail={"code": PHONE_REQUIRED})
  3694. elif request.send_type == "email":
  3695. if not request.email:
  3696. raise HTTPException(status_code=400, detail={"code": EMAIL_REQUIRED})
  3697. else:
  3698. raise HTTPException(status_code=400, detail={"code": SEND_TYPE_INVALID})
  3699. if not request.code:
  3700. raise HTTPException(status_code=400, detail={"code": CODE_REQUIRED})
  3701. # 查询有效的验证码
  3702. async with db_manager.get_session() as session:
  3703. if request.send_type in ["domestic_sms", "international_sms"]:
  3704. result = await session.execute(
  3705. select(VerificationCode)
  3706. .where(
  3707. VerificationCode.phone == request.phone,
  3708. VerificationCode.send_type == request.send_type,
  3709. VerificationCode.code == request.code,
  3710. VerificationCode.is_valid == True
  3711. )
  3712. .order_by(VerificationCode.created_at.desc())
  3713. .limit(1)
  3714. )
  3715. else:
  3716. result = await session.execute(
  3717. select(VerificationCode)
  3718. .where(
  3719. VerificationCode.email == request.email,
  3720. VerificationCode.send_type == request.send_type,
  3721. VerificationCode.code == request.code,
  3722. VerificationCode.is_valid == True
  3723. )
  3724. .order_by(VerificationCode.created_at.desc())
  3725. .limit(1)
  3726. )
  3727. verification_code = result.scalar_one_or_none()
  3728. if verification_code:
  3729. # 验证成功,将验证码标记为无效(一次性使用)
  3730. verification_code.is_valid = False
  3731. await session.commit()
  3732. logger.info(f"✅ 验证码验证成功: phone={request.phone}, email={request.email}, send_type={request.send_type}")
  3733. return {
  3734. "success": True,
  3735. "data": {
  3736. "valid": True,
  3737. "message": "验证成功"
  3738. }
  3739. }
  3740. else:
  3741. logger.warning(f"❌ 验证码验证失败: phone={request.phone}, email={request.email}, code={request.code}")
  3742. return {
  3743. "success": True,
  3744. "data": {
  3745. "valid": False,
  3746. "message": "验证码错误或已失效"
  3747. }
  3748. }
  3749. except HTTPException:
  3750. raise
  3751. except Exception as e:
  3752. logger.exception("验证验证码失败")
  3753. raise HTTPException(status_code=500, detail={"code": VERIFY_CODE_FAILED})
  3754. @app.post("/api/auth/verify-and-auth")
  3755. async def verify_and_auth(request: VerifyAndAuthRequest):
  3756. """
  3757. V2.0:验证码通过后统一登录或注册。
  3758. 返回 { success, data: { user_id, token, expires_at, is_new_user, ... } }
  3759. """
  3760. if request.type not in ("email", "phone"):
  3761. raise HTTPException(status_code=400, detail={"code": TYPE_MUST_BE_EMAIL_OR_PHONE})
  3762. try:
  3763. user, is_new_user = await user_service.verify_and_auth(
  3764. auth_type=request.type,
  3765. code=request.code,
  3766. email=request.email,
  3767. phone=request.phone,
  3768. area_code=request.area_code,
  3769. preferred_language=request.preferred_language,
  3770. )
  3771. session_data = await _generate_session_token(user["user_id"])
  3772. user.update(session_data)
  3773. user["is_new_user"] = is_new_user
  3774. return {"success": True, "data": user}
  3775. except AuthError as e:
  3776. raise HTTPException(status_code=400, detail={"code": e.code})
  3777. except Exception as e:
  3778. logger.exception("verify-and-auth 失败")
  3779. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  3780. @app.get("/api/users/{user_id}/community-choice")
  3781. async def get_community_choice(user_id: str, _: None = Depends(require_user_session)) -> Dict[str, Any]:
  3782. """V2.0:获取用户「退出早期共创社区」选项(登录页回显)"""
  3783. try:
  3784. data = await user_service.get_community_choice(user_id)
  3785. return {"success": True, "data": data or {"opted_out": False}}
  3786. except Exception as e:
  3787. logger.exception("获取 community-choice 失败")
  3788. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  3789. @app.put("/api/users/{user_id}/community-choice")
  3790. async def update_community_choice(
  3791. user_id: str,
  3792. request: CommunityChoiceRequest,
  3793. _: None = Depends(require_user_session),
  3794. ):
  3795. """V2.0:更新用户「退出早期共创社区」选项"""
  3796. try:
  3797. await user_service.upsert_community_choice(user_id, request.opted_out)
  3798. return {"success": True}
  3799. except Exception as e:
  3800. logger.exception("更新 community-choice 失败")
  3801. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  3802. @app.get("/api/users/{user_id}/early-community")
  3803. async def get_early_community(user_id: str, _: None = Depends(require_user_session)) -> Dict[str, Any]:
  3804. """V2.0:获取用户早期共创状态(是否已展示弹窗、是否已留邮箱)"""
  3805. try:
  3806. data = await user_service.get_early_community(user_id)
  3807. return {"success": True, "data": data or {}}
  3808. except Exception as e:
  3809. logger.exception("获取 early-community 失败")
  3810. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  3811. @app.post("/api/users/{user_id}/early-community")
  3812. async def submit_early_community(
  3813. user_id: str,
  3814. request: EarlyCommunityRequest,
  3815. _: None = Depends(require_user_session),
  3816. ):
  3817. """V2.0:提交早期共创(标记弹窗已展示,可选留邮箱)"""
  3818. try:
  3819. data = await user_service.submit_early_community(user_id, request.email)
  3820. return {"success": True, "data": data}
  3821. except Exception as e:
  3822. logger.exception("提交 early-community 失败")
  3823. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  3824. @app.get("/api/users/{user_id}/ui-state")
  3825. async def get_user_ui_state(user_id: str, _: None = Depends(require_user_session)) -> Dict[str, Any]:
  3826. """
  3827. 获取用户前端可视化状态(页面、路由、提示状态)
  3828. """
  3829. try:
  3830. state = await user_service.get_user_ui_state(user_id)
  3831. user = await user_service.get_user(user_id)
  3832. special_group = user.get("special_group") if user else None
  3833. if not state:
  3834. # 没有记录时返回默认值
  3835. default_subtitle_on = await ab_subtitle_service.resolve_subtitle_on(special_group, False)
  3836. default_state = UserUIStateResponse(
  3837. user_id=user_id,
  3838. current_page=None,
  3839. visited_routes=[],
  3840. subtitle_on=default_subtitle_on,
  3841. )
  3842. return {"success": True, "data": default_state.dict()}
  3843. if "subtitle_on" in state:
  3844. state["subtitle_on"] = await ab_subtitle_service.resolve_subtitle_on(
  3845. special_group,
  3846. bool(state.get("subtitle_on")),
  3847. )
  3848. return {"success": True, "data": state}
  3849. except Exception as e: # noqa: BLE001
  3850. logger.exception("获取用户UI状态失败")
  3851. raise HTTPException(status_code=500, detail={"code": GET_UI_STATE_FAILED}) from e
  3852. @app.post("/api/page-visit")
  3853. async def report_page_visit(
  3854. request: PageVisitRequest,
  3855. user_id: Optional[str] = Depends(optional_user_id),
  3856. ) -> Dict[str, Any]:
  3857. """记录一次页面访问(任意界面打开时上报,未登录也可上报)"""
  3858. path = (request.path or "").strip() or "/"
  3859. await user_service.log_page_visit(user_id, path)
  3860. return {"success": True}
  3861. @app.put("/api/users/{user_id}/ui-state")
  3862. async def update_user_ui_state(
  3863. user_id: str,
  3864. request: UpdateUserUIStateRequest,
  3865. _: None = Depends(require_user_session),
  3866. ) -> Dict[str, Any]:
  3867. """
  3868. 更新用户前端可视化状态(部分字段)
  3869. """
  3870. try:
  3871. user = await user_service.get_user(user_id)
  3872. special_group = user.get("special_group") if user else None
  3873. resolved_subtitle_on = request.subtitle_on
  3874. if request.subtitle_on is not None:
  3875. resolved_subtitle_on = await ab_subtitle_service.resolve_subtitle_on(
  3876. special_group,
  3877. bool(request.subtitle_on),
  3878. )
  3879. updated = await user_service.upsert_user_ui_state(
  3880. user_id=user_id,
  3881. current_page=request.current_page,
  3882. visited_routes=request.visited_routes,
  3883. has_shown_tap_to_chat=request.has_shown_tap_to_chat,
  3884. has_shown_cancel_tooltip=request.has_shown_cancel_tooltip,
  3885. has_shown_send_tooltip=request.has_shown_send_tooltip,
  3886. has_shown_progress_bar_tooltip=request.has_shown_progress_bar_tooltip,
  3887. has_shown_mission_stone_modal=request.has_shown_mission_stone_modal,
  3888. has_shown_conversation_stone_modal=request.has_shown_conversation_stone_modal,
  3889. has_clicked_mission_stone=request.has_clicked_mission_stone,
  3890. has_clicked_conversation_stone=request.has_clicked_conversation_stone,
  3891. has_shown_first_shop_tooltip=request.has_shown_first_shop_tooltip,
  3892. has_clicked_shop_in_settings=request.has_clicked_shop_in_settings,
  3893. avatar_c_unlocked=request.avatar_c_unlocked,
  3894. has_shared_avatar=request.has_shared_avatar,
  3895. current_avatar_id=request.current_avatar_id,
  3896. subtitle_on=resolved_subtitle_on,
  3897. sfx_enabled=request.sfx_enabled,
  3898. bgm_enabled=request.bgm_enabled,
  3899. )
  3900. if not updated:
  3901. raise HTTPException(status_code=500, detail={"code": UPDATE_UI_STATE_FAILED})
  3902. if updated and "subtitle_on" in updated:
  3903. updated["subtitle_on"] = await ab_subtitle_service.resolve_subtitle_on(
  3904. special_group,
  3905. bool(updated.get("subtitle_on")),
  3906. )
  3907. return {"success": True, "data": updated}
  3908. except HTTPException:
  3909. raise
  3910. except Exception as e: # noqa: BLE001
  3911. logger.exception("更新用户UI状态失败")
  3912. raise HTTPException(status_code=500, detail={"code": UPDATE_UI_STATE_FAILED}) from e
  3913. @app.get("/api/users/{user_id}/intimacy")
  3914. async def get_user_intimacy(user_id: str, _: None = Depends(require_user_session)) -> Dict[str, Any]:
  3915. """获取用户亲密度:heart_count 0-3,days_since_last_visit 距上次访问天数"""
  3916. try:
  3917. data = await user_service.get_intimacy(user_id)
  3918. return {"success": True, "data": data}
  3919. except Exception as e: # noqa: BLE001
  3920. logger.exception("获取亲密度失败")
  3921. raise HTTPException(status_code=500, detail={"code": "GET_INTIMACY_FAILED"}) from e
  3922. @app.post("/api/users/{user_id}/intimacy/light-up")
  3923. async def light_up_intimacy(user_id: str, _: None = Depends(require_user_session)) -> Dict[str, Any]:
  3924. """点亮一颗心,最多 3 颗"""
  3925. try:
  3926. data = await user_service.light_up_intimacy(user_id)
  3927. return {"success": True, "data": data}
  3928. except Exception as e: # noqa: BLE001
  3929. logger.exception("点亮亲密度失败")
  3930. raise HTTPException(status_code=500, detail={"code": "LIGHT_UP_INTIMACY_FAILED"}) from e
  3931. @app.get("/api/users/{user_id}/intimacy/status")
  3932. async def get_user_intimacy_status(user_id: str, _: None = Depends(require_user_session)) -> Dict[str, Any]:
  3933. """
  3934. 获取用户当天是否可以点亮亲密度。
  3935. 返回:
  3936. {
  3937. "success": true,
  3938. "data": {
  3939. "heart_count": int, # 当前心数 0-3
  3940. "can_light_up_today": bool, # 今天是否还能点亮一次
  3941. }
  3942. }
  3943. """
  3944. try:
  3945. data = await user_service.get_intimacy_status(user_id)
  3946. return {"success": True, "data": data}
  3947. except Exception as e: # noqa: BLE001
  3948. logger.exception("获取亲密度状态失败")
  3949. raise HTTPException(status_code=500, detail={"code": "GET_INTIMACY_STATUS_FAILED"}) from e
  3950. # ==================== OAuth 授权端点 ====================
  3951. @app.get("/api/auth/wechat/authorize")
  3952. async def wechat_authorize(request: Request):
  3953. """
  3954. 获取微信授权URL
  3955. 根据微信官方文档:https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
  3956. - 使用 qrconnect 端点进行网站应用授权
  3957. - scope 必须为 snsapi_login
  3958. - redirect_uri 需要 urlEncode 处理
  3959. - state 用于防止 CSRF 攻击
  3960. Returns:
  3961. 重定向到微信授权页面
  3962. """
  3963. if not settings.WECHAT_OPEN_APP_ID or not settings.WECHAT_REDIRECT_URI:
  3964. raise HTTPException(status_code=500, detail={"code": WECHAT_OAUTH_NOT_CONFIGURED})
  3965. # 生成state参数(用于防止CSRF攻击)
  3966. import secrets
  3967. state = secrets.token_urlsafe(32)
  3968. # 将 state 存储到 Redis(如果可用),用于回调时验证
  3969. # TTL 设置为 10 分钟(code 的有效期也是 10 分钟)
  3970. redis_cache = getattr(request.app.state, 'redis_cache', None)
  3971. if redis_cache:
  3972. try:
  3973. redis_client = await redis_cache._get_redis()
  3974. await redis_client.setex(f"oauth:wechat:state:{state}", 600, "1") # 10分钟过期
  3975. except Exception as e:
  3976. logger.warning(f"存储 state 到 Redis 失败,将跳过验证: {e}")
  3977. # 构建微信授权URL(使用开放平台的AppID)
  3978. # redirect_uri 会自动通过 urlencode 进行编码
  3979. params = {
  3980. "appid": settings.WECHAT_OPEN_APP_ID, # 使用开放平台的AppID
  3981. "redirect_uri": settings.WECHAT_REDIRECT_URI, # urlencode 会自动编码
  3982. "response_type": "code",
  3983. "scope": "snsapi_login", # 网站应用必须使用 snsapi_login
  3984. "state": state,
  3985. }
  3986. # 根据官方文档格式:https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
  3987. auth_url = f"https://open.weixin.qq.com/connect/qrconnect?{urllib.parse.urlencode(params)}#wechat_redirect"
  3988. return RedirectResponse(url=auth_url)
  3989. @app.get("/api/auth/wechat/callback")
  3990. async def wechat_callback(
  3991. request: Request,
  3992. code: str = Query(..., description="微信授权码"),
  3993. state: str = Query(None, description="状态参数")
  3994. ):
  3995. """
  3996. 微信OAuth回调处理
  3997. 根据微信官方文档流程:
  3998. 1. 验证 state 参数(防止 CSRF 攻击)
  3999. 2. 通过 code 换取 access_token
  4000. 3. 使用 openid 进行登录/注册
  4001. Args:
  4002. code: 微信返回的授权码(有效期10分钟,只能使用一次)
  4003. state: 状态参数(用于验证请求合法性)
  4004. Returns:
  4005. 重定向到前端页面(带token)
  4006. """
  4007. try:
  4008. if not settings.WECHAT_OPEN_APP_ID or not settings.WECHAT_OPEN_APP_SECRET:
  4009. raise HTTPException(status_code=500, detail={"code": WECHAT_OAUTH_NOT_CONFIGURED})
  4010. # 1. 验证 state 参数(防止 CSRF 攻击)
  4011. if state:
  4012. redis_cache = getattr(request.app.state, 'redis_cache', None)
  4013. if redis_cache:
  4014. try:
  4015. redis_client = await redis_cache._get_redis()
  4016. state_key = f"oauth:wechat:state:{state}"
  4017. exists = await redis_client.exists(state_key)
  4018. if not exists:
  4019. logger.warning(f"State 验证失败: {state} (可能已过期或被篡改)")
  4020. return RedirectResponse(
  4021. url=f"{settings.FRONTEND_URL}/register?error=wechat_auth_failed&reason=invalid_state"
  4022. )
  4023. # 验证成功后删除 state(一次性使用)
  4024. await redis_client.delete(state_key)
  4025. except Exception as e:
  4026. logger.warning(f"State 验证异常: {e},继续处理")
  4027. # 2. 通过code获取access_token(使用开放平台的AppID和AppSecret)
  4028. # 根据官方文档:https://api.weixin.qq.com/sns/oauth2/access_token
  4029. token_url = "https://api.weixin.qq.com/sns/oauth2/access_token"
  4030. token_params = {
  4031. "appid": settings.WECHAT_OPEN_APP_ID, # 使用开放平台的AppID
  4032. "secret": settings.WECHAT_OPEN_APP_SECRET, # 使用开放平台的AppSecret
  4033. "code": code,
  4034. "grant_type": "authorization_code",
  4035. }
  4036. async with httpx.AsyncClient() as client:
  4037. token_response = await client.get(token_url, params=token_params)
  4038. token_data = token_response.json()
  4039. if "errcode" in token_data:
  4040. logger.error(f"微信获取access_token失败: {token_data}")
  4041. return RedirectResponse(
  4042. url=f"{settings.FRONTEND_URL}/register?error=wechat_auth_failed"
  4043. )
  4044. access_token = token_data.get("access_token")
  4045. openid = token_data.get("openid")
  4046. # refresh_token 可用于刷新 access_token,当前实现暂不保存
  4047. if not access_token or not openid:
  4048. logger.error(f"微信返回数据不完整: {token_data}")
  4049. return RedirectResponse(
  4050. url=f"{settings.FRONTEND_URL}/register?error=wechat_auth_failed"
  4051. )
  4052. # 3. 使用openid登录/注册
  4053. # 注意:当前使用 snsapi_login scope,只能获取 openid
  4054. # 如需获取用户昵称、头像等信息,需要:
  4055. # - 将 scope 改为 snsapi_login,snsapi_userinfo
  4056. # - 调用 /sns/userinfo 接口获取用户信息
  4057. user = await user_service.login_with_wechat(openid=openid)
  4058. # 4. 重定向到前端,携带用户信息
  4059. frontend_url = f"{settings.FRONTEND_URL}/register?oauth=wechat&user_id={user['user_id']}&username={urllib.parse.quote(user['username'])}"
  4060. return RedirectResponse(url=frontend_url)
  4061. except Exception as e:
  4062. logger.error(f"微信OAuth回调处理失败: {e}")
  4063. return RedirectResponse(
  4064. url=f"{settings.FRONTEND_URL}/register?error=wechat_auth_failed"
  4065. )
  4066. @app.get("/api/auth/qq/authorize")
  4067. async def qq_authorize(
  4068. request: Request,
  4069. from_page: str = Query(None, alias="from", description="来源页面"),
  4070. user_id: str = Query(None, description="可选的现有用户ID,如果提供则更新该用户而不是创建新用户")
  4071. ):
  4072. """
  4073. 获取QQ授权URL
  4074. Args:
  4075. from_page: 来源页面(如 first-login),用于回调时决定重定向位置
  4076. user_id: 可选的现有用户ID,如果提供则更新该用户而不是创建新用户
  4077. Returns:
  4078. 重定向到QQ授权页面
  4079. """
  4080. if not settings.QQ_APP_ID or not settings.QQ_REDIRECT_URI:
  4081. raise HTTPException(status_code=500, detail={"code": QQ_OAUTH_NOT_CONFIGURED})
  4082. # 生成state参数(用于防止CSRF攻击)
  4083. import secrets
  4084. state_token = secrets.token_urlsafe(32)
  4085. # state只存储token,from_page和user_id存储在Redis中(避免token包含下划线导致解析错误)
  4086. state = state_token
  4087. # 将 state 存储到 Redis 以便回调校验(存储原始 token 和来源信息)
  4088. redis_cache = getattr(request.app.state, 'redis_cache', None)
  4089. state_stored = False
  4090. state_key = f"oauth:qq:state:{state_token}"
  4091. logger.info(f"📝 [QQ授权] 开始存储state - state_token={state_token}, from_page={from_page}, user_id={user_id}, state={state}, state_key={state_key}")
  4092. if redis_cache:
  4093. try:
  4094. redis_client = await redis_cache._get_redis()
  4095. # 🔥 检查Redis连接状态
  4096. try:
  4097. ping_result = await redis_client.ping()
  4098. logger.debug(f"✅ [QQ授权] Redis连接正常: ping={ping_result}")
  4099. except Exception as ping_err:
  4100. logger.error(f"❌ [QQ授权] Redis ping失败: {ping_err}")
  4101. # 🔥 检查Redis配置信息(DB、连接池等)
  4102. try:
  4103. redis_info = await redis_client.info('server')
  4104. redis_db = redis_client.connection_pool.connection_kwargs.get('db', 0)
  4105. logger.debug(f"🔍 [QQ授权] Redis配置 - DB={redis_db}, server_version={redis_info.get('redis_version', 'unknown')}")
  4106. except Exception as info_err:
  4107. logger.debug(f"⚠️ [QQ授权] 获取Redis信息失败: {info_err}")
  4108. # 🔥 检查key是否已存在(防止重复)
  4109. existing_value = await redis_client.get(state_key)
  4110. if existing_value:
  4111. logger.warning(f"⚠️ [QQ授权] state key已存在,将被覆盖: key={state_key}, old_value={existing_value[:50]}...")
  4112. # 存储原始 token、来源信息和 user_id
  4113. state_data = {"token": state_token}
  4114. if from_page:
  4115. state_data["from"] = from_page
  4116. if user_id:
  4117. state_data["user_id"] = user_id
  4118. state_value = json.dumps(state_data)
  4119. logger.debug(f"📦 [QQ授权] 准备存储 - key={state_key}, value={state_value}, TTL=1800s")
  4120. # 🔥 增加TTL到1800秒(30分钟),避免授权流程过长导致过期
  4121. await redis_client.setex(state_key, 1800, state_value)
  4122. state_stored = True
  4123. # 🔥 验证存储是否成功
  4124. verify_value = await redis_client.get(state_key)
  4125. if verify_value:
  4126. # 🔥 检查TTL
  4127. ttl = await redis_client.ttl(state_key)
  4128. logger.info(f"✅ [QQ授权] QQ state 已存储并验证成功 - key={state_key}, token={state_token[:16]}..., TTL={ttl}s, value_length={len(verify_value)}")
  4129. else:
  4130. logger.error(f"❌ [QQ授权] QQ state 存储后验证失败 - key={state_key}, token={state_token[:16]}...")
  4131. # 🔥 尝试查找所有相关的keys
  4132. try:
  4133. pattern = f"oauth:qq:state:*"
  4134. keys = []
  4135. async for key in redis_client.scan_iter(match=pattern, count=100):
  4136. keys.append(key)
  4137. logger.debug(f"🔍 [QQ授权] Redis中存在的QQ state keys: {keys[:10]}... (共{len(keys)}个)")
  4138. except Exception as scan_err:
  4139. logger.debug(f"🔍 [QQ授权] 扫描keys失败: {scan_err}")
  4140. except Exception as e:
  4141. logger.error(f"❌ [QQ授权] 存储 QQ state 失败 - key={state_key}, error={e}", exc_info=True)
  4142. else:
  4143. logger.warning("⚠️ [QQ授权] Redis缓存服务不可用,QQ state 验证将被跳过")
  4144. # 确保回调地址格式正确(去除末尾斜杠,确保与QQ应用配置完全一致)
  4145. redirect_uri = settings.QQ_REDIRECT_URI.rstrip('/')
  4146. # 构建QQ授权URL
  4147. # 注意:QQ开放平台要求redirect_uri必须与配置的回调域完全匹配
  4148. params = {
  4149. "response_type": "code",
  4150. "client_id": settings.QQ_APP_ID,
  4151. "redirect_uri": redirect_uri, # 使用处理后的回调地址
  4152. "state": state,
  4153. "scope": "get_user_info", # QQ授权范围
  4154. }
  4155. # URL编码参数(确保特殊字符正确编码)
  4156. auth_url = f"https://graph.qq.com/oauth2.0/authorize?{urllib.parse.urlencode(params)}"
  4157. # 调试日志:记录实际发送的授权URL(隐藏敏感信息)
  4158. logger.info(f"🔍 QQ授权URL生成 - AppID: {settings.QQ_APP_ID[:8]}..., 回调地址: {redirect_uri}, 来源: {from_page}")
  4159. return RedirectResponse(url=auth_url)
  4160. @app.get("/api/qq/mp/verify")
  4161. async def qq_callback(
  4162. request: Request,
  4163. code: str = Query(..., description="QQ授权码"),
  4164. state: str = Query(None, description="状态参数")
  4165. ):
  4166. """
  4167. QQ OAuth回调处理
  4168. Args:
  4169. code: QQ返回的授权码
  4170. state: 状态参数
  4171. Returns:
  4172. 重定向到前端页面(带token)
  4173. """
  4174. try:
  4175. logger.info(f"📥 [QQ回调] 收到回调请求 - code={'***' if code else '(empty)'}, state={state}")
  4176. # 0. 验证 state 防止 CSRF,并提取来源信息
  4177. from_page = None
  4178. user_id_from_state = None
  4179. state_token = state # state就是token,不再需要分割
  4180. if state:
  4181. logger.debug(f"🔍 [QQ回调] 开始解析state - state={state}, length={len(state)}")
  4182. redis_cache = getattr(request.app.state, 'redis_cache', None)
  4183. state_key = f"oauth:qq:state:{state_token}"
  4184. logger.info(f"🔑 [QQ回调] 准备验证state - state_token={state_token[:16]}..., state_key={state_key}")
  4185. if redis_cache:
  4186. try:
  4187. redis_client = await redis_cache._get_redis()
  4188. # 🔥 检查Redis连接状态
  4189. try:
  4190. ping_result = await redis_client.ping()
  4191. logger.debug(f"✅ [QQ回调] Redis连接正常: ping={ping_result}")
  4192. except Exception as ping_error:
  4193. logger.error(f"❌ [QQ回调] Redis ping失败: {ping_error}", exc_info=True)
  4194. # Redis连接失败时,跳过验证但记录警告(为了不影响用户体验)
  4195. logger.warning("⚠️ [QQ回调] Redis连接失败,跳过state验证(可能存在安全风险)")
  4196. # 继续处理,不阻止登录流程
  4197. else:
  4198. # 🔥 检查Redis配置信息(DB、连接池等)
  4199. try:
  4200. redis_db = redis_client.connection_pool.connection_kwargs.get('db', 0)
  4201. logger.debug(f"🔍 [QQ回调] Redis配置 - DB={redis_db}")
  4202. except Exception as info_err:
  4203. logger.debug(f"⚠️ [QQ回调] 获取Redis配置失败: {info_err}")
  4204. # 🔥 尝试查找key
  4205. logger.debug(f"🔍 [QQ回调] 开始查找key: {state_key}")
  4206. state_data_str = await redis_client.get(state_key)
  4207. if not state_data_str:
  4208. # 🔥 增加详细日志,帮助诊断问题
  4209. logger.warning(f"❌ [QQ回调] QQ state 验证失败 - state_token={state_token[:16]}..., state_key={state_key}")
  4210. # 🔥 检查key的TTL(如果key存在但值为None,可能是其他问题)
  4211. try:
  4212. exists = await redis_client.exists(state_key)
  4213. logger.debug(f"🔍 [QQ回调] key存在性检查: exists={exists}")
  4214. if exists:
  4215. ttl = await redis_client.ttl(state_key)
  4216. logger.debug(f"🔍 [QQ回调] key存在但值为空,TTL={ttl}s")
  4217. except Exception as exists_err:
  4218. logger.debug(f"🔍 [QQ回调] 检查key存在性失败: {exists_err}")
  4219. # 🔥 尝试查找所有相关的state key(用于调试)
  4220. try:
  4221. pattern = f"oauth:qq:state:*"
  4222. keys = []
  4223. async for key in redis_client.scan_iter(match=pattern, count=100):
  4224. keys.append(key)
  4225. if keys:
  4226. logger.warning(f"🔍 [QQ回调] Redis中存在其他QQ state keys (共{len(keys)}个): {keys[:10]}")
  4227. # 🔥 检查这些keys的TTL
  4228. for key in keys[:5]:
  4229. try:
  4230. ttl = await redis_client.ttl(key)
  4231. value = await redis_client.get(key)
  4232. logger.debug(f"🔍 [QQ回调] key详情 - {key}: TTL={ttl}s, value_length={len(value) if value else 0}")
  4233. except Exception as key_err:
  4234. logger.debug(f"🔍 [QQ回调] 获取key详情失败 {key}: {key_err}")
  4235. else:
  4236. logger.warning(f"🔍 [QQ回调] Redis中不存在任何QQ state keys")
  4237. except Exception as scan_error:
  4238. logger.debug(f"🔍 [QQ回调] 扫描Redis keys失败: {scan_error}")
  4239. return RedirectResponse(
  4240. url=f"{settings.FRONTEND_URL}/register?error=qq_auth_failed&reason=invalid_state"
  4241. )
  4242. # 🔥 找到key,记录详细信息
  4243. ttl = await redis_client.ttl(state_key)
  4244. logger.info(f"✅ [QQ回调] 找到state key - key={state_key}, TTL={ttl}s, value_length={len(state_data_str)}")
  4245. # 如果存储的是 JSON 格式,解析获取来源信息和user_id
  4246. try:
  4247. state_data = json.loads(state_data_str)
  4248. from_page = state_data.get("from") or from_page
  4249. user_id_from_state = state_data.get("user_id")
  4250. logger.info(f"✅ [QQ回调] QQ state 验证成功 - state_token={state_token[:16]}..., 来源: {from_page}, user_id: {user_id_from_state}, data={state_data}")
  4251. except (json.JSONDecodeError, TypeError) as json_err:
  4252. # 如果不是 JSON 格式,使用从 state 中解析的 from_page
  4253. logger.debug(f"✅ [QQ回调] QQ state 验证成功 (非JSON格式) - state_token={state_token[:16]}..., value={state_data_str[:50]}..., json_err={json_err}")
  4254. pass
  4255. # 🔥 删除已使用的state key
  4256. deleted = await redis_client.delete(state_key)
  4257. logger.debug(f"🗑️ [QQ回调] 删除state key - key={state_key}, deleted={deleted}")
  4258. except Exception as state_error:
  4259. logger.error(f"❌ [QQ回调] QQ state 验证异常 - state_token={state_token[:16]}..., error={state_error}", exc_info=True)
  4260. # 🔥 验证异常时不阻止流程,但记录详细错误
  4261. else:
  4262. logger.warning("⚠️ [QQ回调] Redis缓存服务不可用,跳过state验证")
  4263. if not settings.QQ_APP_ID or not settings.QQ_APP_KEY:
  4264. raise HTTPException(status_code=500, detail={"code": QQ_OAUTH_NOT_CONFIGURED})
  4265. # 小工具:解析 QQ JSONP 或 querystring 响应
  4266. def parse_qq_payload(payload_text: str) -> dict:
  4267. cleaned = (payload_text or "").strip()
  4268. if not cleaned:
  4269. return {}
  4270. if cleaned.startswith("callback("):
  4271. cleaned = cleaned.split("callback(", 1)[1]
  4272. cleaned = cleaned.rsplit(");", 1)[0]
  4273. try:
  4274. return json.loads(cleaned)
  4275. except json.JSONDecodeError:
  4276. parsed = {}
  4277. for part in cleaned.split("&"):
  4278. if "=" in part:
  4279. key, value = part.split("=", 1)
  4280. parsed[key] = value
  4281. return parsed
  4282. # 1. 通过code获取access_token
  4283. # 确保回调地址格式正确(与授权时保持一致)
  4284. redirect_uri = settings.QQ_REDIRECT_URI.rstrip('/')
  4285. token_url = "https://graph.qq.com/oauth2.0/token"
  4286. token_params = {
  4287. "grant_type": "authorization_code",
  4288. "client_id": settings.QQ_APP_ID,
  4289. "client_secret": settings.QQ_APP_KEY,
  4290. "code": code,
  4291. "redirect_uri": redirect_uri, # 使用处理后的回调地址
  4292. "fmt": "json",
  4293. }
  4294. logger.info(f"🔍 QQ获取token - 回调地址: {redirect_uri}")
  4295. async with httpx.AsyncClient() as client:
  4296. token_response = await client.get(token_url, params=token_params)
  4297. token_text = token_response.text
  4298. try:
  4299. token_data = token_response.json()
  4300. except ValueError:
  4301. token_data = parse_qq_payload(token_text)
  4302. if "error" in token_data:
  4303. logger.error(f"QQ获取access_token失败: {token_data}")
  4304. return RedirectResponse(
  4305. url=f"{settings.FRONTEND_URL}/register?error=qq_auth_failed&reason=token"
  4306. )
  4307. access_token = token_data.get("access_token")
  4308. if not access_token:
  4309. logger.error(f"QQ返回数据不完整: {token_data}")
  4310. return RedirectResponse(
  4311. url=f"{settings.FRONTEND_URL}/register?error=qq_auth_failed"
  4312. )
  4313. # 2. 通过access_token获取openid
  4314. openid_url = "https://graph.qq.com/oauth2.0/me"
  4315. openid_params = {
  4316. "access_token": access_token,
  4317. "unionid": 1,
  4318. "fmt": "json",
  4319. }
  4320. async with httpx.AsyncClient() as client:
  4321. openid_response = await client.get(openid_url, params=openid_params)
  4322. openid_data = parse_qq_payload(openid_response.text)
  4323. if "error" in openid_data:
  4324. logger.error(f"QQ获取openid失败: {openid_data}")
  4325. return RedirectResponse(
  4326. url=f"{settings.FRONTEND_URL}/register?error=qq_auth_failed"
  4327. )
  4328. openid = openid_data.get("openid")
  4329. unionid = openid_data.get("unionid")
  4330. if not openid:
  4331. logger.error(f"QQ返回openid为空: {openid_data}")
  4332. return RedirectResponse(
  4333. url=f"{settings.FRONTEND_URL}/register?error=qq_auth_failed"
  4334. )
  4335. # 2.1 可选:拉取用户信息用于填充昵称
  4336. nickname = ""
  4337. user_info = {}
  4338. user_info_url = "https://graph.qq.com/user/get_user_info"
  4339. user_info_params = {
  4340. "access_token": access_token,
  4341. "oauth_consumer_key": settings.QQ_APP_ID,
  4342. "openid": openid,
  4343. "fmt": "json",
  4344. }
  4345. try:
  4346. async with httpx.AsyncClient() as client:
  4347. user_info_resp = await client.get(
  4348. user_info_url,
  4349. params=user_info_params,
  4350. )
  4351. user_info = user_info_resp.json()
  4352. if user_info.get("ret") == 0:
  4353. nickname = user_info.get("nickname", "") or ""
  4354. else:
  4355. logger.warning(
  4356. f"QQ用户信息获取失败: {user_info}"
  4357. )
  4358. except Exception as info_error:
  4359. logger.warning(f"拉取QQ用户信息异常: {info_error}")
  4360. # 3. 根据来源页面决定处理逻辑
  4361. if from_page == "login":
  4362. # 从 login 页面来的,需要先检查用户是否存在
  4363. # 如果用户不存在,不允许自动注册,应该提示用户先注册
  4364. logger.info(f"🔍 [QQ回调] 开始检查用户是否存在 - openid={openid[:16]}..., unionid={unionid[:16] if unionid else None}...")
  4365. user_exists = await user_service.check_user_exists_by_qq_openid(openid=openid, unionid=unionid)
  4366. logger.info(f"🔍 [QQ回调] 用户存在性检查结果 - user_exists={user_exists}, openid={openid[:16]}...")
  4367. if not user_exists:
  4368. # 用户不存在,重定向到 begin 页面并提示(和手机号登录保持一致)
  4369. logger.info(f"⚠️ QQ用户未注册(来自login页面): openid={openid[:16]}..., unionid={unionid[:16] if unionid else None}...")
  4370. return RedirectResponse(
  4371. url=f"{settings.FRONTEND_URL}/begin?error=user_not_registered&oauth=qq"
  4372. )
  4373. # 用户存在,使用openid登录
  4374. # 不传递QQ返回的nickname,避免覆盖用户原有用户名
  4375. logger.info(f"✅ [QQ回调] 用户存在,开始登录 - openid={openid[:16]}...")
  4376. user = await user_service.login_with_qq(
  4377. openid=openid,
  4378. username="", # 不使用QQ返回的nickname
  4379. unionid=unionid,
  4380. )
  4381. # 🔧 生成会话 token(前端需要 token 来调用 getUserInfo API)
  4382. session_data = await _generate_session_token(user['user_id'])
  4383. token = session_data['token']
  4384. logger.info(f"✅ [QQ回调] 已生成会话 token - user_id={user['user_id']}, token={token[:16]}...")
  4385. # 重定向到聊天界面(传递 token,避免前端调用 ensureSession 时使用错误的 token)
  4386. logger.info(f"✅ [QQ回调] 登录成功,准备重定向到聊天界面 - user_id={user['user_id']}")
  4387. frontend_url = f"{settings.FRONTEND_URL}/chatbot?oauth=qq&user_id={user['user_id']}&token={token}"
  4388. return RedirectResponse(url=frontend_url)
  4389. elif from_page == "first-login":
  4390. # 从 first-login 页面来的,允许自动注册
  4391. # 如果提供了 user_id,则更新现有用户;否则创建新用户
  4392. # 不传递QQ返回的nickname,避免覆盖用户原有用户名
  4393. user = await user_service.login_with_qq(
  4394. openid=openid,
  4395. username="", # 不使用QQ返回的nickname
  4396. unionid=unionid,
  4397. user_id=user_id_from_state,
  4398. )
  4399. # 重定向到 first-login-reward(不传递username,避免使用QQ返回的nickname)
  4400. frontend_url = f"{settings.FRONTEND_URL}/first-login-reward?oauth=qq&user_id={user['user_id']}"
  4401. return RedirectResponse(url=frontend_url)
  4402. else:
  4403. # 其他来源(如 register 页面),允许自动注册
  4404. # 使用openid登录/注册(login_with_qq 会自动创建新用户)
  4405. # 不传递QQ返回的nickname,避免使用QQ昵称作为用户名
  4406. user = await user_service.login_with_qq(
  4407. openid=openid,
  4408. username="", # 不使用QQ返回的nickname
  4409. unionid=unionid,
  4410. )
  4411. # 默认重定向到聊天界面(不传递username,由前端从数据库同步)
  4412. frontend_url = f"{settings.FRONTEND_URL}/chatbot?oauth=qq&user_id={user['user_id']}"
  4413. return RedirectResponse(url=frontend_url)
  4414. except Exception as e:
  4415. logger.error(f"QQ OAuth回调处理失败: {e}")
  4416. return RedirectResponse(
  4417. url=f"{settings.FRONTEND_URL}/register?error=qq_auth_failed"
  4418. )
  4419. @app.get("/api/wechat/jsapi/config")
  4420. async def get_wechat_jsapi_config(
  4421. url: str = Query(..., description="当前页面URL(用于生成签名)")
  4422. ):
  4423. """
  4424. 获取微信JS-SDK配置(包含签名)
  4425. Args:
  4426. url: 当前页面完整URL(前端传入,用于生成签名)
  4427. Returns:
  4428. {
  4429. "success": true,
  4430. "data": {
  4431. "appId": "微信AppID",
  4432. "timestamp": 1234567890,
  4433. "nonceStr": "随机字符串",
  4434. "signature": "SHA1签名"
  4435. }
  4436. }
  4437. """
  4438. try:
  4439. if not settings.WECHAT_MP_APP_ID:
  4440. logger.error("微信公众平台AppID未配置,请检查环境变量 WECHAT_MP_APP_ID")
  4441. raise HTTPException(status_code=500, detail={"code": WECHAT_MP_NOT_CONFIGURED})
  4442. # 记录接收到的URL(用于调试)
  4443. logger.info(f"📥 收到微信JS-SDK配置请求: url={url[:100]}...")
  4444. # 获取Redis客户端(用于缓存jsapi_ticket)
  4445. from database import db_manager
  4446. redis_getter = db_manager.get_redis
  4447. # 创建微信JS-SDK服务
  4448. jsapi_service = WechatJSAPIService(redis_getter=redis_getter)
  4449. # 获取配置
  4450. config = await jsapi_service.get_jsapi_config(url)
  4451. if not config:
  4452. logger.error("获取微信JS-SDK配置失败(返回None)")
  4453. raise HTTPException(status_code=500, detail={"code": WECHAT_JSAPI_CONFIG_FAILED})
  4454. logger.info(f"✅ 微信JS-SDK配置生成成功: appId={config.get('appId', 'N/A')[:10]}..., timestamp={config.get('timestamp')}")
  4455. return {
  4456. "success": True,
  4457. "data": config
  4458. }
  4459. except HTTPException:
  4460. raise
  4461. except Exception as e:
  4462. logger.error(f"获取微信JS-SDK配置异常: {e}", exc_info=True)
  4463. logger.exception("获取微信JS-SDK配置异常")
  4464. raise HTTPException(status_code=500, detail={"code": GET_CONFIG_FAILED})
  4465. @app.get("/api/qq/share/config")
  4466. async def get_qq_share_config():
  4467. """
  4468. 获取QQ分享配置(包含AppID和应用名称)
  4469. Returns:
  4470. {
  4471. "success": true,
  4472. "data": {
  4473. "appId": "QQ AppID",
  4474. "appName": "应用名称"
  4475. }
  4476. }
  4477. """
  4478. try:
  4479. if not settings.QQ_APP_ID:
  4480. logger.warning("QQ AppID未配置,返回空配置")
  4481. return {
  4482. "success": True,
  4483. "data": {
  4484. "appId": "",
  4485. "appName": settings.QQ_APP_NAME
  4486. }
  4487. }
  4488. logger.info(f"📥 收到QQ分享配置请求: appId={settings.QQ_APP_ID[:8]}..., appName={settings.QQ_APP_NAME}")
  4489. return {
  4490. "success": True,
  4491. "data": {
  4492. "appId": settings.QQ_APP_ID,
  4493. "appName": settings.QQ_APP_NAME
  4494. }
  4495. }
  4496. except Exception as e:
  4497. logger.exception("获取QQ分享配置异常")
  4498. raise HTTPException(status_code=500, detail={"code": GET_CONFIG_FAILED})
  4499. # ==================== 微信公众平台服务器配置 ====================
  4500. @app.get("/api/wechat/mp/verify")
  4501. async def wechat_mp_verify(
  4502. signature: str = Query(..., description="微信加密签名"),
  4503. timestamp: str = Query(..., description="时间戳"),
  4504. nonce: str = Query(..., description="随机数"),
  4505. echostr: str = Query(..., description="随机字符串")
  4506. ):
  4507. """
  4508. 微信公众平台服务器验证接口(GET)
  4509. 用于微信公众平台配置服务器URL时的验证
  4510. Args:
  4511. signature: 微信加密签名
  4512. timestamp: 时间戳
  4513. nonce: 随机数
  4514. echostr: 随机字符串
  4515. Returns:
  4516. 验证成功返回echostr,失败返回空字符串
  4517. """
  4518. if not settings.WECHAT_MP_TOKEN:
  4519. logger.error("微信公众平台Token未配置")
  4520. return PlainTextResponse("", status_code=500)
  4521. try:
  4522. # 1. 将token、timestamp、nonce按字典序排序
  4523. token = settings.WECHAT_MP_TOKEN
  4524. tmp_arr = [token, timestamp, nonce]
  4525. tmp_arr.sort()
  4526. # 2. 拼接字符串并SHA1加密
  4527. tmp_str = ''.join(tmp_arr)
  4528. tmp_str = hashlib.sha1(tmp_str.encode('utf-8')).hexdigest()
  4529. # 3. 与signature比较
  4530. if tmp_str == signature:
  4531. logger.info("✅ 微信公众平台服务器验证成功")
  4532. return PlainTextResponse(echostr)
  4533. else:
  4534. logger.warning(f"⚠️ 微信公众平台服务器验证失败: signature不匹配")
  4535. return PlainTextResponse("", status_code=403)
  4536. except Exception as e:
  4537. logger.error(f"❌ 微信公众平台服务器验证异常: {e}")
  4538. return PlainTextResponse("", status_code=500)
  4539. @app.post("/api/wechat/mp/message")
  4540. async def wechat_mp_message(request: Request):
  4541. """
  4542. 微信公众平台消息推送接口(POST)
  4543. 接收微信公众平台推送的消息(文本、事件等)
  4544. Returns:
  4545. XML格式的响应消息
  4546. """
  4547. if not settings.WECHAT_MP_TOKEN:
  4548. logger.error("微信公众平台Token未配置")
  4549. return PlainTextResponse("", status_code=500)
  4550. try:
  4551. # 1. 获取请求参数(用于验证签名)
  4552. signature = request.query_params.get("signature", "")
  4553. timestamp = request.query_params.get("timestamp", "")
  4554. nonce = request.query_params.get("nonce", "")
  4555. # 2. 验证签名
  4556. token = settings.WECHAT_MP_TOKEN
  4557. tmp_arr = [token, timestamp, nonce]
  4558. tmp_arr.sort()
  4559. tmp_str = ''.join(tmp_arr)
  4560. tmp_str = hashlib.sha1(tmp_str.encode('utf-8')).hexdigest()
  4561. if tmp_str != signature:
  4562. logger.warning(f"⚠️ 微信公众平台消息签名验证失败")
  4563. return PlainTextResponse("", status_code=403)
  4564. # 3. 读取XML消息体
  4565. body = await request.body()
  4566. xml_data = body.decode('utf-8')
  4567. # 4. 解析XML
  4568. root = ET.fromstring(xml_data)
  4569. msg_type = root.find('MsgType').text if root.find('MsgType') is not None else ''
  4570. from_user = root.find('FromUserName').text if root.find('FromUserName') is not None else ''
  4571. to_user = root.find('ToUserName').text if root.find('ToUserName') is not None else ''
  4572. logger.info(f"📨 收到微信公众平台消息: type={msg_type}, from={from_user}")
  4573. # 5. 处理不同类型的消息
  4574. if msg_type == 'text':
  4575. # 文本消息
  4576. content = root.find('Content').text if root.find('Content') is not None else ''
  4577. logger.info(f"📝 文本消息内容: {content}")
  4578. # 回复文本消息(示例:自动回复)
  4579. reply_content = "感谢您的消息!"
  4580. reply_xml = f"""<xml>
  4581. <ToUserName><![CDATA[{from_user}]]></ToUserName>
  4582. <FromUserName><![CDATA[{to_user}]]></FromUserName>
  4583. <CreateTime>{int(__import__('time').time())}</CreateTime>
  4584. <MsgType><![CDATA[text]]></MsgType>
  4585. <Content><![CDATA[{reply_content}]]></Content>
  4586. </xml>"""
  4587. return PlainTextResponse(reply_xml, media_type="application/xml")
  4588. elif msg_type == 'event':
  4589. # 事件消息
  4590. event = root.find('Event').text if root.find('Event') is not None else ''
  4591. logger.info(f"🎯 事件消息: {event}")
  4592. # 处理关注/取消关注事件
  4593. if event == 'subscribe':
  4594. reply_content = "欢迎关注!"
  4595. elif event == 'unsubscribe':
  4596. reply_content = "感谢您的关注!"
  4597. else:
  4598. reply_content = "收到事件消息"
  4599. reply_xml = f"""<xml>
  4600. <ToUserName><![CDATA[{from_user}]]></ToUserName>
  4601. <FromUserName><![CDATA[{to_user}]]></FromUserName>
  4602. <CreateTime>{int(__import__('time').time())}</CreateTime>
  4603. <MsgType><![CDATA[text]]></MsgType>
  4604. <Content><![CDATA[{reply_content}]]></Content>
  4605. </xml>"""
  4606. return PlainTextResponse(reply_xml, media_type="application/xml")
  4607. else:
  4608. # 其他类型消息,返回空响应
  4609. logger.info(f"ℹ️ 未处理的消息类型: {msg_type}")
  4610. return PlainTextResponse("success")
  4611. except Exception as e:
  4612. logger.error(f"❌ 处理微信公众平台消息异常: {e}")
  4613. return PlainTextResponse("success") # 返回success避免微信重试
  4614. @app.post("/api/admin/inbox/energy-gifts")
  4615. async def admin_create_energy_gift_inbox(payload: AdminCreateEnergyGiftInboxRequest):
  4616. """创建能量石赠送站内信(指定用户)。"""
  4617. user_ids = payload.user_ids
  4618. now = datetime.utcnow()
  4619. try:
  4620. async with db_manager.get_session() as session:
  4621. insert_message_sql = text(
  4622. """
  4623. INSERT INTO inbox_messages (
  4624. message_type, title, title_en, content, content_en, target_type, energy_stone_amount, created_by
  4625. ) VALUES (
  4626. 'energy_gift', :title_zh, :title_en, :content_zh, :content_en, 'users', :energy_stone_amount, 'web-admin'
  4627. )
  4628. """
  4629. )
  4630. result = await session.execute(
  4631. insert_message_sql,
  4632. {
  4633. "title_zh": payload.title_zh.strip(),
  4634. "title_en": payload.title_en.strip(),
  4635. "content_zh": payload.content_zh.strip(),
  4636. "content_en": payload.content_en.strip(),
  4637. "energy_stone_amount": payload.energy_stone_amount,
  4638. },
  4639. )
  4640. message_id = int(result.lastrowid)
  4641. insert_target_sql = text(
  4642. """
  4643. INSERT INTO inbox_message_targets (message_id, user_id, created_at)
  4644. VALUES (:message_id, :user_id, :created_at)
  4645. ON DUPLICATE KEY UPDATE created_at = VALUES(created_at)
  4646. """
  4647. )
  4648. for uid in user_ids:
  4649. await session.execute(
  4650. insert_target_sql,
  4651. {"message_id": message_id, "user_id": uid, "created_at": now},
  4652. )
  4653. await session.commit()
  4654. return {"success": True, "data": {"message_id": message_id, "created_count": len(user_ids)}}
  4655. except Exception:
  4656. logger.exception("创建能量石站内信失败")
  4657. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4658. @app.post("/api/admin/inbox/news")
  4659. async def admin_create_news_inbox(payload: AdminCreateNewsInboxRequest):
  4660. """创建消息通知站内信(创建即发送,全员)。"""
  4661. try:
  4662. async with db_manager.get_session() as session:
  4663. insert_sql = text(
  4664. """
  4665. INSERT INTO inbox_messages (
  4666. message_type, title, title_en, content, content_en, target_type, energy_stone_amount, created_by
  4667. ) VALUES (
  4668. 'news_notice', :title_zh, :title_en, :content_zh, :content_en, 'all_users', 0, 'web-admin'
  4669. )
  4670. """
  4671. )
  4672. result = await session.execute(
  4673. insert_sql,
  4674. {
  4675. "title_zh": payload.title_zh.strip(),
  4676. "title_en": payload.title_en.strip(),
  4677. "content_zh": payload.content_zh.strip(),
  4678. "content_en": payload.content_en.strip(),
  4679. },
  4680. )
  4681. await session.commit()
  4682. return {"success": True, "data": {"message_id": int(result.lastrowid)}}
  4683. except Exception:
  4684. logger.exception("创建消息通知站内信失败")
  4685. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4686. @app.post("/api/admin/inbox/ab-notices")
  4687. async def admin_create_ab_notice_inbox(payload: AdminCreateNewsInboxRequest):
  4688. """创建 A/B 实验组消息通知(仅 is_special_user 且 A/B 组用户)。"""
  4689. now = datetime.utcnow()
  4690. try:
  4691. async with db_manager.get_session() as session:
  4692. users_sql = text(
  4693. """
  4694. SELECT user_id
  4695. FROM users
  4696. WHERE is_special_user = 1 AND special_group IN ('A', 'B')
  4697. """
  4698. )
  4699. user_rows = (await session.execute(users_sql)).mappings().all()
  4700. user_ids = [str(row["user_id"]) for row in user_rows if row.get("user_id")]
  4701. if not user_ids:
  4702. raise HTTPException(status_code=400, detail={"code": "NO_AB_USERS", "message": "未找到 A/B 实验组用户"})
  4703. insert_message_sql = text(
  4704. """
  4705. INSERT INTO inbox_messages (
  4706. message_type, title, title_en, content, content_en, target_type, energy_stone_amount, created_by
  4707. ) VALUES (
  4708. 'ab_notice', :title_zh, :title_en, :content_zh, :content_en, 'users', 0, 'web-admin'
  4709. )
  4710. """
  4711. )
  4712. result = await session.execute(
  4713. insert_message_sql,
  4714. {
  4715. "title_zh": payload.title_zh.strip(),
  4716. "title_en": payload.title_en.strip(),
  4717. "content_zh": payload.content_zh.strip(),
  4718. "content_en": payload.content_en.strip(),
  4719. },
  4720. )
  4721. message_id = int(result.lastrowid)
  4722. insert_target_sql = text(
  4723. """
  4724. INSERT INTO inbox_message_targets (message_id, user_id, created_at)
  4725. VALUES (:message_id, :user_id, :created_at)
  4726. ON DUPLICATE KEY UPDATE created_at = VALUES(created_at)
  4727. """
  4728. )
  4729. for uid in user_ids:
  4730. await session.execute(
  4731. insert_target_sql,
  4732. {"message_id": message_id, "user_id": uid, "created_at": now},
  4733. )
  4734. await session.commit()
  4735. return {"success": True, "data": {"message_id": message_id, "created_count": len(user_ids)}}
  4736. except HTTPException:
  4737. raise
  4738. except Exception:
  4739. logger.exception("创建 A/B 实验组消息通知失败")
  4740. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4741. @app.get("/api/admin/llm-tasks")
  4742. async def admin_list_llm_tasks(
  4743. page: int = Query(1, ge=1),
  4744. page_size: int = Query(20, ge=1, le=100),
  4745. ):
  4746. """A/B 实验:LLM 任务列表(web-admin)。"""
  4747. try:
  4748. data = await llm_task_service.list_tasks(page=page, page_size=page_size)
  4749. return {"success": True, "data": data}
  4750. except Exception:
  4751. logger.exception("查询 LLM 任务列表失败")
  4752. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4753. @app.post("/api/admin/llm-tasks")
  4754. async def admin_create_llm_task(payload: AdminCreateLlmTaskRequest):
  4755. """A/B 实验:新建 LLM 任务(新建即成为当前最新任务)。"""
  4756. try:
  4757. task = await llm_task_service.create_task(
  4758. task_name=payload.task_name.strip(),
  4759. task_prompt=payload.task_prompt.strip(),
  4760. lumi_first_line=payload.lumi_first_line.strip(),
  4761. )
  4762. return {"success": True, "data": task}
  4763. except ValueError as e:
  4764. raise HTTPException(status_code=400, detail={"code": "INVALID_PARAMS", "message": str(e)})
  4765. except Exception:
  4766. logger.exception("创建 LLM 任务失败")
  4767. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4768. @app.put("/api/admin/llm-tasks/{task_id}")
  4769. async def admin_update_llm_task(task_id: int, payload: AdminUpdateLlmTaskRequest):
  4770. """A/B 实验:更新 LLM 任务。"""
  4771. try:
  4772. task = await llm_task_service.update_task(
  4773. task_id=task_id,
  4774. task_name=payload.task_name.strip(),
  4775. task_prompt=payload.task_prompt.strip(),
  4776. lumi_first_line=payload.lumi_first_line.strip(),
  4777. )
  4778. if not task:
  4779. raise HTTPException(status_code=404, detail={"code": "NOT_FOUND"})
  4780. return {"success": True, "data": task}
  4781. except HTTPException:
  4782. raise
  4783. except ValueError as e:
  4784. raise HTTPException(status_code=400, detail={"code": "INVALID_PARAMS", "message": str(e)})
  4785. except Exception:
  4786. logger.exception("更新 LLM 任务失败")
  4787. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4788. @app.delete("/api/admin/llm-tasks/{task_id}")
  4789. async def admin_delete_llm_task(task_id: int):
  4790. """A/B 实验:删除 LLM 任务。"""
  4791. try:
  4792. deleted = await llm_task_service.delete_task(task_id)
  4793. if not deleted:
  4794. raise HTTPException(status_code=404, detail={"code": "NOT_FOUND"})
  4795. return {"success": True, "data": None}
  4796. except HTTPException:
  4797. raise
  4798. except Exception:
  4799. logger.exception("删除 LLM 任务失败")
  4800. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4801. @app.get("/api/admin/ab-subtitle-settings")
  4802. async def admin_list_ab_subtitle_settings():
  4803. """A/B 实验:字幕开关配置列表(web-admin)。"""
  4804. try:
  4805. data = await ab_subtitle_service.list_settings()
  4806. return {"success": True, "data": data}
  4807. except Exception:
  4808. logger.exception("查询 A/B 字幕配置失败")
  4809. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4810. @app.put("/api/admin/ab-subtitle-settings/{group_key}")
  4811. async def admin_update_ab_subtitle_setting(
  4812. group_key: str,
  4813. payload: AdminUpdateAbSubtitleSettingRequest,
  4814. ):
  4815. """A/B 实验:更新某组字幕开关(0=关,1=开)。"""
  4816. try:
  4817. row = await ab_subtitle_service.update_setting(
  4818. group_key=group_key.strip().upper(),
  4819. subtitle_on=payload.subtitle_on,
  4820. )
  4821. if not row:
  4822. raise HTTPException(status_code=404, detail={"code": "NOT_FOUND"})
  4823. return {"success": True, "data": row}
  4824. except HTTPException:
  4825. raise
  4826. except ValueError as e:
  4827. raise HTTPException(status_code=400, detail={"code": "INVALID_PARAMS", "message": str(e)})
  4828. except Exception:
  4829. logger.exception("更新 A/B 字幕配置失败")
  4830. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4831. @app.get("/api/admin/users")
  4832. async def admin_list_users(
  4833. keyword: Optional[str] = Query(None, description="按 user_id/username/email/phone 模糊搜索"),
  4834. page: int = Query(1, ge=1),
  4835. page_size: int = Query(20, ge=1, le=100),
  4836. ):
  4837. """供 web-admin 选择用户列表使用。"""
  4838. offset = (page - 1) * page_size
  4839. kw = (keyword or "").strip()
  4840. try:
  4841. async with db_manager.get_session() as session:
  4842. if kw:
  4843. like_kw = f"%{kw}%"
  4844. list_sql = text(
  4845. """
  4846. SELECT user_id, username, email, phone
  4847. FROM users
  4848. WHERE user_id LIKE :kw
  4849. OR username LIKE :kw
  4850. OR email LIKE :kw
  4851. OR phone LIKE :kw
  4852. ORDER BY id DESC
  4853. LIMIT :limit OFFSET :offset
  4854. """
  4855. )
  4856. count_sql = text(
  4857. """
  4858. SELECT COUNT(1)
  4859. FROM users
  4860. WHERE user_id LIKE :kw
  4861. OR username LIKE :kw
  4862. OR email LIKE :kw
  4863. OR phone LIKE :kw
  4864. """
  4865. )
  4866. params: Dict[str, Any] = {"kw": like_kw, "limit": page_size, "offset": offset}
  4867. else:
  4868. list_sql = text(
  4869. """
  4870. SELECT user_id, username, email, phone
  4871. FROM users
  4872. ORDER BY id DESC
  4873. LIMIT :limit OFFSET :offset
  4874. """
  4875. )
  4876. count_sql = text("SELECT COUNT(1) FROM users")
  4877. params = {"limit": page_size, "offset": offset}
  4878. rows = (await session.execute(list_sql, params)).mappings().all()
  4879. total = int((await session.execute(count_sql, {"kw": f"%{kw}%"} if kw else {})).scalar_one())
  4880. items = [
  4881. {
  4882. "user_id": row["user_id"],
  4883. "username": row["username"],
  4884. "email": row["email"],
  4885. "phone": row["phone"],
  4886. }
  4887. for row in rows
  4888. ]
  4889. return {"success": True, "data": {"items": items, "total": total, "page": page, "page_size": page_size}}
  4890. except Exception:
  4891. logger.exception("查询管理端用户列表失败")
  4892. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4893. @app.get("/api/admin/inbox/messages")
  4894. async def admin_list_inbox_messages(
  4895. message_type: Optional[str] = Query(None, description="energy_gift/news_notice/ab_notice"),
  4896. title_keyword: Optional[str] = Query(None, description="标题关键字"),
  4897. start_date: Optional[str] = Query(None, description="开始日期,格式 YYYY-MM-DD"),
  4898. end_date: Optional[str] = Query(None, description="结束日期,格式 YYYY-MM-DD"),
  4899. page: int = Query(1, ge=1),
  4900. page_size: int = Query(20, ge=1, le=100),
  4901. ):
  4902. """管理端站内信历史列表。"""
  4903. if message_type and message_type not in ADMIN_INBOX_MESSAGE_TYPES:
  4904. raise HTTPException(status_code=400, detail="invalid message_type")
  4905. offset = (page - 1) * page_size
  4906. where_clauses: list[str] = []
  4907. params: Dict[str, Any] = {"limit": page_size, "offset": offset}
  4908. if message_type:
  4909. where_clauses.append("m.message_type = :message_type")
  4910. params["message_type"] = message_type
  4911. if title_keyword and title_keyword.strip():
  4912. where_clauses.append("(m.title LIKE :title_keyword OR COALESCE(m.title_en, '') LIKE :title_keyword)")
  4913. params["title_keyword"] = f"%{title_keyword.strip()}%"
  4914. if start_date and start_date.strip():
  4915. where_clauses.append("DATE(m.created_at) >= :start_date")
  4916. params["start_date"] = start_date.strip()
  4917. if end_date and end_date.strip():
  4918. where_clauses.append("DATE(m.created_at) <= :end_date")
  4919. params["end_date"] = end_date.strip()
  4920. where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
  4921. try:
  4922. async with db_manager.get_session() as session:
  4923. list_sql = text(
  4924. f"""
  4925. SELECT
  4926. m.id,
  4927. m.message_type,
  4928. m.title,
  4929. COALESCE(m.title_en, '') AS title_en,
  4930. m.target_type,
  4931. m.energy_stone_amount,
  4932. m.created_at,
  4933. CASE
  4934. WHEN m.target_type = 'all_users' THEN (SELECT COUNT(1) FROM users)
  4935. ELSE COALESCE(t.target_count, 0)
  4936. END AS target_count,
  4937. COALESCE(s.read_count, 0) AS read_count,
  4938. COALESCE(s.claim_count, 0) AS claim_count
  4939. FROM inbox_messages m
  4940. LEFT JOIN (
  4941. SELECT message_id, COUNT(1) AS target_count
  4942. FROM inbox_message_targets
  4943. GROUP BY message_id
  4944. ) t ON m.id = t.message_id
  4945. LEFT JOIN (
  4946. SELECT
  4947. message_id,
  4948. SUM(CASE WHEN read_status = 1 THEN 1 ELSE 0 END) AS read_count,
  4949. SUM(CASE WHEN claim_status = 1 THEN 1 ELSE 0 END) AS claim_count
  4950. FROM inbox_user_message_states
  4951. GROUP BY message_id
  4952. ) s ON m.id = s.message_id
  4953. {where_sql}
  4954. ORDER BY m.created_at DESC, m.id DESC
  4955. LIMIT :limit OFFSET :offset
  4956. """
  4957. )
  4958. count_sql = text(
  4959. f"""
  4960. SELECT COUNT(1)
  4961. FROM inbox_messages m
  4962. {where_sql}
  4963. """
  4964. )
  4965. rows = (await session.execute(list_sql, params)).mappings().all()
  4966. count_params = {k: v for k, v in params.items() if k not in {"limit", "offset"}}
  4967. total = int((await session.execute(count_sql, count_params)).scalar_one())
  4968. items = [
  4969. {
  4970. "id": int(row["id"]),
  4971. "message_type": row["message_type"],
  4972. "title": row["title"],
  4973. "title_zh": row["title"],
  4974. "title_en": row["title_en"],
  4975. "target_type": row["target_type"],
  4976. "energy_stone_amount": int(row["energy_stone_amount"] or 0),
  4977. "target_count": int(row["target_count"] or 0),
  4978. "read_count": int(row["read_count"] or 0),
  4979. "claim_count": int(row["claim_count"] or 0),
  4980. "created_at": row["created_at"].isoformat() if row["created_at"] else None,
  4981. }
  4982. for row in rows
  4983. ]
  4984. return {"success": True, "data": {"items": items, "total": total, "page": page, "page_size": page_size}}
  4985. except Exception:
  4986. logger.exception("查询管理端站内信历史失败")
  4987. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  4988. @app.get("/api/admin/inbox/messages/{message_id}")
  4989. async def admin_get_inbox_message_detail(
  4990. message_id: int,
  4991. page: int = Query(1, ge=1),
  4992. page_size: int = Query(50, ge=1, le=200),
  4993. ):
  4994. """管理端站内信详情(含用户阅读/领取状态)。"""
  4995. offset = (page - 1) * page_size
  4996. try:
  4997. async with db_manager.get_session() as session:
  4998. message_sql = text(
  4999. """
  5000. SELECT id, message_type, title, COALESCE(title_en, '') AS title_en, content, COALESCE(content_en, '') AS content_en, target_type, energy_stone_amount, created_at
  5001. FROM inbox_messages
  5002. WHERE id = :message_id
  5003. LIMIT 1
  5004. """
  5005. )
  5006. message_row = (await session.execute(message_sql, {"message_id": message_id})).mappings().first()
  5007. if not message_row:
  5008. raise HTTPException(status_code=404, detail="message not found")
  5009. summary_sql = text(
  5010. """
  5011. SELECT
  5012. COALESCE(SUM(CASE WHEN read_status = 1 THEN 1 ELSE 0 END), 0) AS read_count,
  5013. COALESCE(SUM(CASE WHEN claim_status = 1 THEN 1 ELSE 0 END), 0) AS claim_count
  5014. FROM inbox_user_message_states
  5015. WHERE message_id = :message_id
  5016. """
  5017. )
  5018. summary_row = (await session.execute(summary_sql, {"message_id": message_id})).mappings().first()
  5019. read_count = int(summary_row["read_count"] or 0) if summary_row else 0
  5020. claim_count = int(summary_row["claim_count"] or 0) if summary_row else 0
  5021. if message_row["target_type"] == "all_users":
  5022. target_count = int((await session.execute(text("SELECT COUNT(1) FROM users"))).scalar_one())
  5023. state_list_sql = text(
  5024. """
  5025. SELECT
  5026. s.user_id,
  5027. u.username,
  5028. u.phone,
  5029. u.email,
  5030. s.read_status,
  5031. s.claim_status,
  5032. s.deleted_status
  5033. FROM inbox_user_message_states s
  5034. LEFT JOIN users u ON s.user_id = u.user_id
  5035. WHERE s.message_id = :message_id
  5036. ORDER BY s.updated_at DESC, s.id DESC
  5037. LIMIT :limit OFFSET :offset
  5038. """
  5039. )
  5040. state_count_sql = text(
  5041. "SELECT COUNT(1) FROM inbox_user_message_states WHERE message_id = :message_id"
  5042. )
  5043. state_rows = (
  5044. await session.execute(
  5045. state_list_sql, {"message_id": message_id, "limit": page_size, "offset": offset}
  5046. )
  5047. ).mappings().all()
  5048. state_total = int((await session.execute(state_count_sql, {"message_id": message_id})).scalar_one())
  5049. else:
  5050. target_count_sql = text(
  5051. "SELECT COUNT(1) FROM inbox_message_targets WHERE message_id = :message_id"
  5052. )
  5053. target_count = int((await session.execute(target_count_sql, {"message_id": message_id})).scalar_one())
  5054. state_list_sql = text(
  5055. """
  5056. SELECT
  5057. t.user_id,
  5058. u.username,
  5059. u.phone,
  5060. u.email,
  5061. COALESCE(s.read_status, 0) AS read_status,
  5062. COALESCE(s.claim_status, 0) AS claim_status,
  5063. COALESCE(s.deleted_status, 0) AS deleted_status
  5064. FROM inbox_message_targets t
  5065. LEFT JOIN users u ON t.user_id = u.user_id
  5066. LEFT JOIN inbox_user_message_states s
  5067. ON s.message_id = t.message_id AND s.user_id = t.user_id
  5068. WHERE t.message_id = :message_id
  5069. ORDER BY t.id DESC
  5070. LIMIT :limit OFFSET :offset
  5071. """
  5072. )
  5073. state_count_sql = text("SELECT COUNT(1) FROM inbox_message_targets WHERE message_id = :message_id")
  5074. state_rows = (
  5075. await session.execute(
  5076. state_list_sql, {"message_id": message_id, "limit": page_size, "offset": offset}
  5077. )
  5078. ).mappings().all()
  5079. state_total = int((await session.execute(state_count_sql, {"message_id": message_id})).scalar_one())
  5080. state_items = [
  5081. {
  5082. "user_id": row["user_id"],
  5083. "username": row["username"],
  5084. "phone": row["phone"],
  5085. "email": row["email"],
  5086. "read_status": int(row["read_status"] or 0),
  5087. "claim_status": int(row["claim_status"] or 0),
  5088. "deleted_status": int(row["deleted_status"] or 0),
  5089. }
  5090. for row in state_rows
  5091. ]
  5092. return {
  5093. "success": True,
  5094. "data": {
  5095. "message": {
  5096. "id": int(message_row["id"]),
  5097. "message_type": message_row["message_type"],
  5098. "title": message_row["title"],
  5099. "title_zh": message_row["title"],
  5100. "title_en": message_row["title_en"],
  5101. "content": message_row["content"],
  5102. "content_zh": message_row["content"],
  5103. "content_en": message_row["content_en"],
  5104. "target_type": message_row["target_type"],
  5105. "energy_stone_amount": int(message_row["energy_stone_amount"] or 0),
  5106. "created_at": message_row["created_at"].isoformat() if message_row["created_at"] else None,
  5107. "target_count": target_count,
  5108. "read_count": read_count,
  5109. "claim_count": claim_count,
  5110. },
  5111. "states": {
  5112. "items": state_items,
  5113. "total": state_total,
  5114. "page": page,
  5115. "page_size": page_size,
  5116. },
  5117. },
  5118. }
  5119. except HTTPException:
  5120. raise
  5121. except Exception:
  5122. logger.exception("查询管理端站内信详情失败")
  5123. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  5124. @app.delete("/api/admin/inbox/messages/{message_id}")
  5125. async def admin_delete_inbox_message(message_id: int):
  5126. """管理端删除站内信(物理删除消息与关联状态)。"""
  5127. try:
  5128. async with db_manager.get_session() as session:
  5129. exists_sql = text("SELECT id FROM inbox_messages WHERE id = :message_id LIMIT 1")
  5130. exists_row = (await session.execute(exists_sql, {"message_id": message_id})).mappings().first()
  5131. if not exists_row:
  5132. raise HTTPException(status_code=404, detail="message not found")
  5133. await session.execute(
  5134. text("DELETE FROM inbox_user_message_states WHERE message_id = :message_id"),
  5135. {"message_id": message_id},
  5136. )
  5137. await session.execute(
  5138. text("DELETE FROM inbox_message_targets WHERE message_id = :message_id"),
  5139. {"message_id": message_id},
  5140. )
  5141. await session.execute(
  5142. text("DELETE FROM inbox_messages WHERE id = :message_id"),
  5143. {"message_id": message_id},
  5144. )
  5145. await session.commit()
  5146. return {"success": True}
  5147. except HTTPException:
  5148. raise
  5149. except Exception:
  5150. logger.exception("管理端删除站内信失败")
  5151. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  5152. @app.post("/api/admin/chat-export")
  5153. async def admin_export_chat_messages(
  5154. file: UploadFile = File(..., description="用户手机号或邮箱 txt 文件,每行一个"),
  5155. start_date: Optional[str] = Form(None, description="开始日期 YYYY-MM-DD,留空则导出全部"),
  5156. end_date: Optional[str] = Form(None, description="结束日期 YYYY-MM-DD,留空则导出全部"),
  5157. ):
  5158. """导出指定用户在时间范围内的聊天记录,每个用户一个 Excel,每天一个 Sheet。"""
  5159. start: date | None = None
  5160. end: date | None = None
  5161. start_raw = (start_date or "").strip()
  5162. end_raw = (end_date or "").strip()
  5163. if start_raw or end_raw:
  5164. if not start_raw or not end_raw:
  5165. raise HTTPException(
  5166. status_code=400,
  5167. detail={"code": "INVALID_PARAMS", "message": "开始日期和结束日期需同时提供,或同时留空"},
  5168. )
  5169. try:
  5170. start = datetime.strptime(start_raw, "%Y-%m-%d").date()
  5171. end = datetime.strptime(end_raw, "%Y-%m-%d").date()
  5172. except ValueError:
  5173. raise HTTPException(status_code=400, detail={"code": "INVALID_PARAMS", "message": "日期格式应为 YYYY-MM-DD"})
  5174. raw_bytes = await file.read()
  5175. if not raw_bytes:
  5176. raise HTTPException(status_code=400, detail={"code": "INVALID_PARAMS", "message": "上传文件不能为空"})
  5177. try:
  5178. content = raw_bytes.decode("utf-8-sig")
  5179. except UnicodeDecodeError:
  5180. raise HTTPException(status_code=400, detail={"code": "INVALID_PARAMS", "message": "txt 文件需为 UTF-8 编码"})
  5181. identifiers = parse_identifiers_from_txt(content)
  5182. try:
  5183. async with db_manager.get_session() as session:
  5184. zip_bytes, meta = await export_chat_records_zip(session, identifiers, start, end)
  5185. except ValueError as e:
  5186. raise HTTPException(status_code=400, detail={"code": "INVALID_PARAMS", "message": str(e)})
  5187. except Exception:
  5188. logger.exception("导出聊天记录失败")
  5189. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  5190. filename = (
  5191. f"chat_export_{start.isoformat()}_{end.isoformat()}.zip"
  5192. if start is not None and end is not None
  5193. else "chat_export_all.zip"
  5194. )
  5195. headers = {
  5196. "Content-Disposition": f'attachment; filename="{filename}"',
  5197. "X-Export-Count": str(meta["exported_count"]),
  5198. "X-Not-Found-Count": str(meta["not_found_count"]),
  5199. }
  5200. return StreamingResponse(
  5201. io.BytesIO(zip_bytes),
  5202. media_type="application/zip",
  5203. headers=headers,
  5204. )
  5205. @app.get("/api/users/{user_id}/inbox/messages")
  5206. async def get_user_inbox_messages(
  5207. user_id: str,
  5208. page: int = Query(1, ge=1),
  5209. page_size: int = Query(20, ge=1, le=100),
  5210. message_type: Optional[str] = Query(None, description="energy_gift/news_notice/ab_notice"),
  5211. _: None = Depends(require_user_session),
  5212. ):
  5213. """查询用户站内信列表(仅返回当前用户未删除消息)。"""
  5214. if message_type and message_type not in ADMIN_INBOX_MESSAGE_TYPES:
  5215. raise HTTPException(status_code=400, detail="invalid message_type")
  5216. offset = (page - 1) * page_size
  5217. try:
  5218. async with db_manager.get_session() as session:
  5219. where_type_clause = "AND m.message_type = :message_type" if message_type else ""
  5220. list_sql = text(
  5221. f"""
  5222. SELECT
  5223. m.id,
  5224. m.message_type,
  5225. m.title,
  5226. COALESCE(m.title_en, '') AS title_en,
  5227. m.energy_stone_amount,
  5228. m.created_at,
  5229. COALESCE(s.read_status, 0) AS read_status,
  5230. COALESCE(s.claim_status, 0) AS claim_status
  5231. FROM inbox_messages m
  5232. LEFT JOIN inbox_message_targets t
  5233. ON m.id = t.message_id AND t.user_id = :user_id
  5234. LEFT JOIN inbox_user_message_states s
  5235. ON m.id = s.message_id AND s.user_id = :user_id
  5236. WHERE
  5237. (m.target_type = 'all_users' OR t.user_id IS NOT NULL)
  5238. AND COALESCE(s.deleted_status, 0) = 0
  5239. {where_type_clause}
  5240. ORDER BY m.created_at DESC, m.id DESC
  5241. LIMIT :limit OFFSET :offset
  5242. """
  5243. )
  5244. count_sql = text(
  5245. f"""
  5246. SELECT COUNT(1) AS total
  5247. FROM inbox_messages m
  5248. LEFT JOIN inbox_message_targets t
  5249. ON m.id = t.message_id AND t.user_id = :user_id
  5250. LEFT JOIN inbox_user_message_states s
  5251. ON m.id = s.message_id AND s.user_id = :user_id
  5252. WHERE
  5253. (m.target_type = 'all_users' OR t.user_id IS NOT NULL)
  5254. AND COALESCE(s.deleted_status, 0) = 0
  5255. {where_type_clause}
  5256. """
  5257. )
  5258. params: Dict[str, Any] = {"user_id": user_id, "limit": page_size, "offset": offset}
  5259. if message_type:
  5260. params["message_type"] = message_type
  5261. rows = (await session.execute(list_sql, params)).mappings().all()
  5262. total = int((await session.execute(count_sql, params)).scalar_one())
  5263. items = []
  5264. for row in rows:
  5265. items.append(
  5266. {
  5267. "id": int(row["id"]),
  5268. "type": row["message_type"],
  5269. "title": row["title"],
  5270. "title_zh": row["title"],
  5271. "title_en": row["title_en"],
  5272. "energy_stone_amount": int(row["energy_stone_amount"] or 0),
  5273. "read_status": int(row["read_status"]),
  5274. "claim_status": int(row["claim_status"]),
  5275. "created_at": row["created_at"].isoformat() if row["created_at"] else None,
  5276. }
  5277. )
  5278. return {"success": True, "data": {"items": items, "total": total, "page": page, "page_size": page_size}}
  5279. except Exception:
  5280. logger.exception("查询站内信列表失败")
  5281. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  5282. @app.get("/api/users/{user_id}/inbox/messages/{message_id}")
  5283. async def get_user_inbox_message_detail(
  5284. user_id: str,
  5285. message_id: int,
  5286. mark_read: bool = Query(True),
  5287. _: None = Depends(require_user_session),
  5288. ):
  5289. """查询站内信详情,默认标记为已读。"""
  5290. try:
  5291. async with db_manager.get_session() as session:
  5292. detail_sql = text(
  5293. """
  5294. SELECT
  5295. m.id,
  5296. m.message_type,
  5297. m.title,
  5298. COALESCE(m.title_en, '') AS title_en,
  5299. m.content,
  5300. COALESCE(m.content_en, '') AS content_en,
  5301. m.energy_stone_amount,
  5302. m.created_at,
  5303. COALESCE(s.read_status, 0) AS read_status,
  5304. COALESCE(s.deleted_status, 0) AS deleted_status,
  5305. COALESCE(s.claim_status, 0) AS claim_status
  5306. FROM inbox_messages m
  5307. LEFT JOIN inbox_message_targets t
  5308. ON m.id = t.message_id AND t.user_id = :user_id
  5309. LEFT JOIN inbox_user_message_states s
  5310. ON m.id = s.message_id AND s.user_id = :user_id
  5311. WHERE
  5312. m.id = :message_id
  5313. AND (m.target_type = 'all_users' OR t.user_id IS NOT NULL)
  5314. LIMIT 1
  5315. """
  5316. )
  5317. row = (await session.execute(detail_sql, {"user_id": user_id, "message_id": message_id})).mappings().first()
  5318. if not row or int(row["deleted_status"]) == 1:
  5319. raise HTTPException(status_code=404, detail="message not found")
  5320. if mark_read and int(row["read_status"]) == 0:
  5321. upsert_read_sql = text(
  5322. """
  5323. INSERT INTO inbox_user_message_states (
  5324. message_id, user_id, read_status, read_at
  5325. ) VALUES (
  5326. :message_id, :user_id, 1, NOW()
  5327. )
  5328. ON DUPLICATE KEY UPDATE
  5329. read_status = 1,
  5330. read_at = IFNULL(read_at, NOW())
  5331. """
  5332. )
  5333. await session.execute(upsert_read_sql, {"message_id": message_id, "user_id": user_id})
  5334. await session.commit()
  5335. return {
  5336. "success": True,
  5337. "data": {
  5338. "id": int(row["id"]),
  5339. "type": row["message_type"],
  5340. "title": row["title"],
  5341. "title_zh": row["title"],
  5342. "title_en": row["title_en"],
  5343. "content": row["content"],
  5344. "content_zh": row["content"],
  5345. "content_en": row["content_en"],
  5346. "energy_stone_amount": int(row["energy_stone_amount"] or 0),
  5347. "read_status": 1 if mark_read else int(row["read_status"]),
  5348. "claim_status": int(row["claim_status"]),
  5349. "created_at": row["created_at"].isoformat() if row["created_at"] else None,
  5350. },
  5351. }
  5352. except HTTPException:
  5353. raise
  5354. except Exception:
  5355. logger.exception("查询站内信详情失败")
  5356. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  5357. @app.post("/api/users/{user_id}/inbox/messages/{message_id}/read")
  5358. async def mark_user_inbox_message_read(
  5359. user_id: str, message_id: int, _: None = Depends(require_user_session)
  5360. ):
  5361. """显式标记消息已读。"""
  5362. try:
  5363. async with db_manager.get_session() as session:
  5364. upsert_sql = text(
  5365. """
  5366. INSERT INTO inbox_user_message_states (message_id, user_id, read_status, read_at)
  5367. VALUES (:message_id, :user_id, 1, NOW())
  5368. ON DUPLICATE KEY UPDATE
  5369. read_status = 1,
  5370. read_at = IFNULL(read_at, NOW())
  5371. """
  5372. )
  5373. await session.execute(upsert_sql, {"message_id": message_id, "user_id": user_id})
  5374. await session.commit()
  5375. return {"success": True}
  5376. except Exception:
  5377. logger.exception("标记站内信已读失败")
  5378. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  5379. @app.post("/api/users/{user_id}/inbox/messages/{message_id}/claim")
  5380. async def claim_user_inbox_energy_stones(
  5381. user_id: str, message_id: int, _: None = Depends(require_user_session)
  5382. ):
  5383. """领取能量石站内信奖励(幂等:每条仅可领取一次)。"""
  5384. try:
  5385. async with db_manager.get_session() as session:
  5386. message_sql = text(
  5387. """
  5388. SELECT
  5389. m.id,
  5390. m.message_type,
  5391. m.energy_stone_amount
  5392. FROM inbox_messages m
  5393. LEFT JOIN inbox_message_targets t
  5394. ON m.id = t.message_id AND t.user_id = :user_id
  5395. WHERE
  5396. m.id = :message_id
  5397. AND (m.target_type = 'all_users' OR t.user_id IS NOT NULL)
  5398. LIMIT 1
  5399. """
  5400. )
  5401. message_row = (
  5402. await session.execute(message_sql, {"user_id": user_id, "message_id": message_id})
  5403. ).mappings().first()
  5404. if not message_row:
  5405. raise HTTPException(status_code=404, detail="message not found")
  5406. if message_row["message_type"] != "energy_gift":
  5407. raise HTTPException(status_code=400, detail="message is not energy gift")
  5408. state_sql = text(
  5409. """
  5410. SELECT id, claim_status
  5411. FROM inbox_user_message_states
  5412. WHERE message_id = :message_id AND user_id = :user_id
  5413. FOR UPDATE
  5414. """
  5415. )
  5416. state_row = (
  5417. await session.execute(state_sql, {"message_id": message_id, "user_id": user_id})
  5418. ).mappings().first()
  5419. if state_row and int(state_row["claim_status"]) == 1:
  5420. raise HTTPException(status_code=409, detail="already claimed")
  5421. amount = int(message_row["energy_stone_amount"] or 0)
  5422. if amount <= 0:
  5423. raise HTTPException(status_code=400, detail="invalid energy amount")
  5424. update_user_sql = text(
  5425. """
  5426. UPDATE users
  5427. SET conversation_energy_stone_total = conversation_energy_stone_total + :amount
  5428. WHERE user_id = :user_id
  5429. """
  5430. )
  5431. update_result = await session.execute(update_user_sql, {"amount": amount, "user_id": user_id})
  5432. if int(update_result.rowcount or 0) <= 0:
  5433. raise HTTPException(status_code=404, detail="user not found")
  5434. if state_row:
  5435. update_state_sql = text(
  5436. """
  5437. UPDATE inbox_user_message_states
  5438. SET claim_status = 1,
  5439. claimed_energy_stones = :amount,
  5440. claimed_at = NOW(),
  5441. read_status = 1,
  5442. read_at = IFNULL(read_at, NOW()),
  5443. updated_at = NOW()
  5444. WHERE message_id = :message_id AND user_id = :user_id
  5445. """
  5446. )
  5447. await session.execute(update_state_sql, {"amount": amount, "message_id": message_id, "user_id": user_id})
  5448. else:
  5449. insert_state_sql = text(
  5450. """
  5451. INSERT INTO inbox_user_message_states (
  5452. message_id, user_id, read_status, claim_status,
  5453. claimed_energy_stones, read_at, claimed_at
  5454. ) VALUES (
  5455. :message_id, :user_id, 1, 1,
  5456. :amount, NOW(), NOW()
  5457. )
  5458. """
  5459. )
  5460. await session.execute(insert_state_sql, {"message_id": message_id, "user_id": user_id, "amount": amount})
  5461. total_sql = text("SELECT conversation_energy_stone_total FROM users WHERE user_id = :user_id LIMIT 1")
  5462. total_count = int((await session.execute(total_sql, {"user_id": user_id})).scalar_one())
  5463. await session.commit()
  5464. return {"success": True, "data": {"claimed_energy_stones": amount, "user_total_energy_stones": total_count}}
  5465. except HTTPException:
  5466. raise
  5467. except Exception:
  5468. logger.exception("领取站内信能量石失败")
  5469. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  5470. @app.delete("/api/users/{user_id}/inbox/messages/{message_id}")
  5471. async def delete_user_inbox_message(
  5472. user_id: str, message_id: int, _: None = Depends(require_user_session)
  5473. ):
  5474. """删除消息通知(用户维度软删除)。"""
  5475. try:
  5476. async with db_manager.get_session() as session:
  5477. message_sql = text(
  5478. """
  5479. SELECT
  5480. m.id,
  5481. m.message_type
  5482. FROM inbox_messages m
  5483. LEFT JOIN inbox_message_targets t
  5484. ON m.id = t.message_id AND t.user_id = :user_id
  5485. WHERE
  5486. m.id = :message_id
  5487. AND (m.target_type = 'all_users' OR t.user_id IS NOT NULL)
  5488. LIMIT 1
  5489. """
  5490. )
  5491. message_row = (
  5492. await session.execute(message_sql, {"user_id": user_id, "message_id": message_id})
  5493. ).mappings().first()
  5494. if not message_row:
  5495. raise HTTPException(status_code=404, detail="message not found")
  5496. if message_row["message_type"] not in DELETABLE_INBOX_MESSAGE_TYPES:
  5497. raise HTTPException(status_code=400, detail="energy gift message cannot be deleted")
  5498. upsert_sql = text(
  5499. """
  5500. INSERT INTO inbox_user_message_states (
  5501. message_id, user_id, deleted_status, deleted_at
  5502. ) VALUES (
  5503. :message_id, :user_id, 1, NOW()
  5504. )
  5505. ON DUPLICATE KEY UPDATE
  5506. deleted_status = 1,
  5507. deleted_at = NOW()
  5508. """
  5509. )
  5510. await session.execute(upsert_sql, {"message_id": message_id, "user_id": user_id})
  5511. await session.commit()
  5512. return {"success": True}
  5513. except HTTPException:
  5514. raise
  5515. except Exception:
  5516. logger.exception("删除站内信失败")
  5517. raise HTTPException(status_code=500, detail={"code": SERVER_ERROR})
  5518. @app.websocket("/ws")
  5519. async def websocket_endpoint(websocket: WebSocket):
  5520. """WebSocket端点"""
  5521. # 从查询参数获取user_id(Lyrria_user_id)与会话token
  5522. user_id = websocket.query_params.get("user_id")
  5523. token = websocket.query_params.get("token")
  5524. # 记录连接信息
  5525. import logging
  5526. logger = logging.getLogger(__name__)
  5527. logger.info(
  5528. f"🔌 WebSocket连接: user_id={user_id}, query_params={dict(websocket.query_params)}"
  5529. )
  5530. # 🔥 传入Redis缓存服务、user_id、session_store
  5531. redis_cache = getattr(app.state, 'redis_cache', None)
  5532. session_store = getattr(app.state, "session_store", None)
  5533. handler = WebSocketHandler(
  5534. websocket,
  5535. user_id=user_id,
  5536. token=token,
  5537. redis_cache=redis_cache,
  5538. session_store=session_store,
  5539. )
  5540. await handler.handle_connection()
  5541. if __name__ == "__main__":
  5542. import uvicorn
  5543. import os
  5544. import socket
  5545. from pathlib import Path
  5546. # 🔥 DNS预解析(减少首次连接延迟)
  5547. dashscope_domain = get_dashscope_domain()
  5548. try:
  5549. socket.getaddrinfo(dashscope_domain, 443)
  5550. except Exception as e:
  5551. pass
  5552. # SSL证书路径配置
  5553. # 优先使用环境变量配置的证书路径(生产环境)
  5554. ssl_keyfile = settings.SSL_KEYFILE
  5555. ssl_certfile = settings.SSL_CERTFILE
  5556. # 如果环境变量未配置,使用本地开发证书
  5557. if not ssl_keyfile or not ssl_certfile:
  5558. ssl_dir = Path(__file__).parent.parent / "ssl"
  5559. ssl_keyfile = str(ssl_dir / "key.pem")
  5560. ssl_certfile = str(ssl_dir / "cert.pem")
  5561. # 检查证书是否存在
  5562. if ssl_keyfile and ssl_certfile:
  5563. if not os.path.exists(ssl_keyfile) or not os.path.exists(ssl_certfile):
  5564. ssl_keyfile = None
  5565. ssl_certfile = None
  5566. uvicorn.run(
  5567. "main:app",
  5568. host=settings.host,
  5569. port=settings.port,
  5570. reload=settings.DEBUG,
  5571. ssl_keyfile=ssl_keyfile,
  5572. ssl_certfile=ssl_certfile,
  5573. )