main.py 233 KB

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