main.py 200 KB

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