main.py 200 KB

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