channel.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "github.com/QuantumNous/new-api/common"
  9. "github.com/QuantumNous/new-api/constant"
  10. "github.com/QuantumNous/new-api/dto"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/QuantumNous/new-api/relay/channel/volcengine"
  13. "github.com/QuantumNous/new-api/service"
  14. "github.com/gin-gonic/gin"
  15. )
  16. type OpenAIModel struct {
  17. ID string `json:"id"`
  18. Object string `json:"object"`
  19. Created int64 `json:"created"`
  20. OwnedBy string `json:"owned_by"`
  21. Permission []struct {
  22. ID string `json:"id"`
  23. Object string `json:"object"`
  24. Created int64 `json:"created"`
  25. AllowCreateEngine bool `json:"allow_create_engine"`
  26. AllowSampling bool `json:"allow_sampling"`
  27. AllowLogprobs bool `json:"allow_logprobs"`
  28. AllowSearchIndices bool `json:"allow_search_indices"`
  29. AllowView bool `json:"allow_view"`
  30. AllowFineTuning bool `json:"allow_fine_tuning"`
  31. Organization string `json:"organization"`
  32. Group string `json:"group"`
  33. IsBlocking bool `json:"is_blocking"`
  34. } `json:"permission"`
  35. Root string `json:"root"`
  36. Parent string `json:"parent"`
  37. }
  38. type OpenAIModelsResponse struct {
  39. Data []OpenAIModel `json:"data"`
  40. Success bool `json:"success"`
  41. }
  42. func parseStatusFilter(statusParam string) int {
  43. switch strings.ToLower(statusParam) {
  44. case "enabled", "1":
  45. return common.ChannelStatusEnabled
  46. case "disabled", "0":
  47. return 0
  48. default:
  49. return -1
  50. }
  51. }
  52. func clearChannelInfo(channel *model.Channel) {
  53. if channel.ChannelInfo.IsMultiKey {
  54. channel.ChannelInfo.MultiKeyDisabledReason = nil
  55. channel.ChannelInfo.MultiKeyDisabledTime = nil
  56. }
  57. }
  58. func GetAllChannels(c *gin.Context) {
  59. pageInfo := common.GetPageQuery(c)
  60. channelData := make([]*model.Channel, 0)
  61. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  62. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  63. statusParam := c.Query("status")
  64. // statusFilter: -1 all, 1 enabled, 0 disabled (include auto & manual)
  65. statusFilter := parseStatusFilter(statusParam)
  66. // type filter
  67. typeStr := c.Query("type")
  68. typeFilter := -1
  69. if typeStr != "" {
  70. if t, err := strconv.Atoi(typeStr); err == nil {
  71. typeFilter = t
  72. }
  73. }
  74. var total int64
  75. if enableTagMode {
  76. tags, err := model.GetPaginatedTags(pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  77. if err != nil {
  78. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  79. return
  80. }
  81. for _, tag := range tags {
  82. if tag == nil || *tag == "" {
  83. continue
  84. }
  85. tagChannels, err := model.GetChannelsByTag(*tag, idSort, false)
  86. if err != nil {
  87. continue
  88. }
  89. filtered := make([]*model.Channel, 0)
  90. for _, ch := range tagChannels {
  91. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  92. continue
  93. }
  94. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  95. continue
  96. }
  97. if typeFilter >= 0 && ch.Type != typeFilter {
  98. continue
  99. }
  100. filtered = append(filtered, ch)
  101. }
  102. channelData = append(channelData, filtered...)
  103. }
  104. total, _ = model.CountAllTags()
  105. } else {
  106. baseQuery := model.DB.Model(&model.Channel{})
  107. if typeFilter >= 0 {
  108. baseQuery = baseQuery.Where("type = ?", typeFilter)
  109. }
  110. if statusFilter == common.ChannelStatusEnabled {
  111. baseQuery = baseQuery.Where("status = ?", common.ChannelStatusEnabled)
  112. } else if statusFilter == 0 {
  113. baseQuery = baseQuery.Where("status != ?", common.ChannelStatusEnabled)
  114. }
  115. baseQuery.Count(&total)
  116. order := "priority desc"
  117. if idSort {
  118. order = "id desc"
  119. }
  120. err := baseQuery.Order(order).Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("key").Find(&channelData).Error
  121. if err != nil {
  122. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  123. return
  124. }
  125. }
  126. for _, datum := range channelData {
  127. clearChannelInfo(datum)
  128. }
  129. countQuery := model.DB.Model(&model.Channel{})
  130. if statusFilter == common.ChannelStatusEnabled {
  131. countQuery = countQuery.Where("status = ?", common.ChannelStatusEnabled)
  132. } else if statusFilter == 0 {
  133. countQuery = countQuery.Where("status != ?", common.ChannelStatusEnabled)
  134. }
  135. var results []struct {
  136. Type int64
  137. Count int64
  138. }
  139. _ = countQuery.Select("type, count(*) as count").Group("type").Find(&results).Error
  140. typeCounts := make(map[int64]int64)
  141. for _, r := range results {
  142. typeCounts[r.Type] = r.Count
  143. }
  144. common.ApiSuccess(c, gin.H{
  145. "items": channelData,
  146. "total": total,
  147. "page": pageInfo.GetPage(),
  148. "page_size": pageInfo.GetPageSize(),
  149. "type_counts": typeCounts,
  150. })
  151. return
  152. }
  153. func FetchUpstreamModels(c *gin.Context) {
  154. id, err := strconv.Atoi(c.Param("id"))
  155. if err != nil {
  156. common.ApiError(c, err)
  157. return
  158. }
  159. channel, err := model.GetChannelById(id, true)
  160. if err != nil {
  161. common.ApiError(c, err)
  162. return
  163. }
  164. baseURL := constant.ChannelBaseURLs[channel.Type]
  165. if channel.GetBaseURL() != "" {
  166. baseURL = channel.GetBaseURL()
  167. }
  168. var url string
  169. switch channel.Type {
  170. case constant.ChannelTypeGemini:
  171. // curl https://example.com/v1beta/models?key=$GEMINI_API_KEY
  172. url = fmt.Sprintf("%s/v1beta/openai/models", baseURL) // Remove key in url since we need to use AuthHeader
  173. case constant.ChannelTypeAli:
  174. url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
  175. case constant.ChannelTypeZhipu_v4:
  176. url = fmt.Sprintf("%s/api/paas/v4/models", baseURL)
  177. case constant.ChannelTypeVolcEngine:
  178. if baseURL == volcengine.DoubaoCodingPlan {
  179. url = fmt.Sprintf("%s/v1/models", volcengine.DoubaoCodingPlanOpenAIBaseURL)
  180. } else {
  181. url = fmt.Sprintf("%s/v1/models", baseURL)
  182. }
  183. default:
  184. url = fmt.Sprintf("%s/v1/models", baseURL)
  185. }
  186. // 获取用于请求的可用密钥(多密钥渠道优先使用启用状态的密钥)
  187. key, _, apiErr := channel.GetNextEnabledKey()
  188. if apiErr != nil {
  189. c.JSON(http.StatusOK, gin.H{
  190. "success": false,
  191. "message": fmt.Sprintf("获取渠道密钥失败: %s", apiErr.Error()),
  192. })
  193. return
  194. }
  195. key = strings.TrimSpace(key)
  196. // 获取响应体 - 根据渠道类型决定是否添加 AuthHeader
  197. var body []byte
  198. switch channel.Type {
  199. case constant.ChannelTypeAnthropic:
  200. body, err = GetResponseBody("GET", url, channel, GetClaudeAuthHeader(key))
  201. default:
  202. body, err = GetResponseBody("GET", url, channel, GetAuthHeader(key))
  203. }
  204. if err != nil {
  205. common.ApiError(c, err)
  206. return
  207. }
  208. var result OpenAIModelsResponse
  209. if err = json.Unmarshal(body, &result); err != nil {
  210. c.JSON(http.StatusOK, gin.H{
  211. "success": false,
  212. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  213. })
  214. return
  215. }
  216. var ids []string
  217. for _, model := range result.Data {
  218. id := model.ID
  219. if channel.Type == constant.ChannelTypeGemini {
  220. id = strings.TrimPrefix(id, "models/")
  221. }
  222. ids = append(ids, id)
  223. }
  224. c.JSON(http.StatusOK, gin.H{
  225. "success": true,
  226. "message": "",
  227. "data": ids,
  228. })
  229. }
  230. func FixChannelsAbilities(c *gin.Context) {
  231. success, fails, err := model.FixAbility()
  232. if err != nil {
  233. common.ApiError(c, err)
  234. return
  235. }
  236. c.JSON(http.StatusOK, gin.H{
  237. "success": true,
  238. "message": "",
  239. "data": gin.H{
  240. "success": success,
  241. "fails": fails,
  242. },
  243. })
  244. }
  245. func SearchChannels(c *gin.Context) {
  246. keyword := c.Query("keyword")
  247. group := c.Query("group")
  248. modelKeyword := c.Query("model")
  249. statusParam := c.Query("status")
  250. statusFilter := parseStatusFilter(statusParam)
  251. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  252. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  253. channelData := make([]*model.Channel, 0)
  254. if enableTagMode {
  255. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  256. if err != nil {
  257. c.JSON(http.StatusOK, gin.H{
  258. "success": false,
  259. "message": err.Error(),
  260. })
  261. return
  262. }
  263. for _, tag := range tags {
  264. if tag != nil && *tag != "" {
  265. tagChannel, err := model.GetChannelsByTag(*tag, idSort, false)
  266. if err == nil {
  267. channelData = append(channelData, tagChannel...)
  268. }
  269. }
  270. }
  271. } else {
  272. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  273. if err != nil {
  274. c.JSON(http.StatusOK, gin.H{
  275. "success": false,
  276. "message": err.Error(),
  277. })
  278. return
  279. }
  280. channelData = channels
  281. }
  282. if statusFilter == common.ChannelStatusEnabled || statusFilter == 0 {
  283. filtered := make([]*model.Channel, 0, len(channelData))
  284. for _, ch := range channelData {
  285. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  286. continue
  287. }
  288. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  289. continue
  290. }
  291. filtered = append(filtered, ch)
  292. }
  293. channelData = filtered
  294. }
  295. // calculate type counts for search results
  296. typeCounts := make(map[int64]int64)
  297. for _, channel := range channelData {
  298. typeCounts[int64(channel.Type)]++
  299. }
  300. typeParam := c.Query("type")
  301. typeFilter := -1
  302. if typeParam != "" {
  303. if tp, err := strconv.Atoi(typeParam); err == nil {
  304. typeFilter = tp
  305. }
  306. }
  307. if typeFilter >= 0 {
  308. filtered := make([]*model.Channel, 0, len(channelData))
  309. for _, ch := range channelData {
  310. if ch.Type == typeFilter {
  311. filtered = append(filtered, ch)
  312. }
  313. }
  314. channelData = filtered
  315. }
  316. page, _ := strconv.Atoi(c.DefaultQuery("p", "1"))
  317. pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
  318. if page < 1 {
  319. page = 1
  320. }
  321. if pageSize <= 0 {
  322. pageSize = 20
  323. }
  324. total := len(channelData)
  325. startIdx := (page - 1) * pageSize
  326. if startIdx > total {
  327. startIdx = total
  328. }
  329. endIdx := startIdx + pageSize
  330. if endIdx > total {
  331. endIdx = total
  332. }
  333. pagedData := channelData[startIdx:endIdx]
  334. for _, datum := range pagedData {
  335. clearChannelInfo(datum)
  336. }
  337. c.JSON(http.StatusOK, gin.H{
  338. "success": true,
  339. "message": "",
  340. "data": gin.H{
  341. "items": pagedData,
  342. "total": total,
  343. "type_counts": typeCounts,
  344. },
  345. })
  346. return
  347. }
  348. func GetChannel(c *gin.Context) {
  349. id, err := strconv.Atoi(c.Param("id"))
  350. if err != nil {
  351. common.ApiError(c, err)
  352. return
  353. }
  354. channel, err := model.GetChannelById(id, false)
  355. if err != nil {
  356. common.ApiError(c, err)
  357. return
  358. }
  359. if channel != nil {
  360. clearChannelInfo(channel)
  361. }
  362. c.JSON(http.StatusOK, gin.H{
  363. "success": true,
  364. "message": "",
  365. "data": channel,
  366. })
  367. return
  368. }
  369. // GetChannelKey 获取渠道密钥(需要通过安全验证中间件)
  370. // 此函数依赖 SecureVerificationRequired 中间件,确保用户已通过安全验证
  371. func GetChannelKey(c *gin.Context) {
  372. userId := c.GetInt("id")
  373. channelId, err := strconv.Atoi(c.Param("id"))
  374. if err != nil {
  375. common.ApiError(c, fmt.Errorf("渠道ID格式错误: %v", err))
  376. return
  377. }
  378. // 获取渠道信息(包含密钥)
  379. channel, err := model.GetChannelById(channelId, true)
  380. if err != nil {
  381. common.ApiError(c, fmt.Errorf("获取渠道信息失败: %v", err))
  382. return
  383. }
  384. if channel == nil {
  385. common.ApiError(c, fmt.Errorf("渠道不存在"))
  386. return
  387. }
  388. // 记录操作日志
  389. model.RecordLog(userId, model.LogTypeSystem, fmt.Sprintf("查看渠道密钥信息 (渠道ID: %d)", channelId))
  390. // 返回渠道密钥
  391. c.JSON(http.StatusOK, gin.H{
  392. "success": true,
  393. "message": "获取成功",
  394. "data": map[string]interface{}{
  395. "key": channel.Key,
  396. },
  397. })
  398. }
  399. // validateTwoFactorAuth 统一的2FA验证函数
  400. func validateTwoFactorAuth(twoFA *model.TwoFA, code string) bool {
  401. // 尝试验证TOTP
  402. if cleanCode, err := common.ValidateNumericCode(code); err == nil {
  403. if isValid, _ := twoFA.ValidateTOTPAndUpdateUsage(cleanCode); isValid {
  404. return true
  405. }
  406. }
  407. // 尝试验证备用码
  408. if isValid, err := twoFA.ValidateBackupCodeAndUpdateUsage(code); err == nil && isValid {
  409. return true
  410. }
  411. return false
  412. }
  413. // validateChannel 通用的渠道校验函数
  414. func validateChannel(channel *model.Channel, isAdd bool) error {
  415. // 校验 channel settings
  416. if err := channel.ValidateSettings(); err != nil {
  417. return fmt.Errorf("渠道额外设置[channel setting] 格式错误:%s", err.Error())
  418. }
  419. // 如果是添加操作,检查 channel 和 key 是否为空
  420. if isAdd {
  421. if channel == nil || channel.Key == "" {
  422. return fmt.Errorf("channel cannot be empty")
  423. }
  424. // 检查模型名称长度是否超过 255
  425. for _, m := range channel.GetModels() {
  426. if len(m) > 255 {
  427. return fmt.Errorf("模型名称过长: %s", m)
  428. }
  429. }
  430. }
  431. // VertexAI 特殊校验
  432. if channel.Type == constant.ChannelTypeVertexAi {
  433. if channel.Other == "" {
  434. return fmt.Errorf("部署地区不能为空")
  435. }
  436. regionMap, err := common.StrToMap(channel.Other)
  437. if err != nil {
  438. return fmt.Errorf("部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}")
  439. }
  440. if regionMap["default"] == nil {
  441. return fmt.Errorf("部署地区必须包含default字段")
  442. }
  443. }
  444. return nil
  445. }
  446. type AddChannelRequest struct {
  447. Mode string `json:"mode"`
  448. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  449. BatchAddSetKeyPrefix2Name bool `json:"batch_add_set_key_prefix_2_name"`
  450. Channel *model.Channel `json:"channel"`
  451. }
  452. func getVertexArrayKeys(keys string) ([]string, error) {
  453. if keys == "" {
  454. return nil, nil
  455. }
  456. var keyArray []interface{}
  457. err := common.Unmarshal([]byte(keys), &keyArray)
  458. if err != nil {
  459. return nil, fmt.Errorf("批量添加 Vertex AI 必须使用标准的JsonArray格式,例如[{key1}, {key2}...],请检查输入: %w", err)
  460. }
  461. cleanKeys := make([]string, 0, len(keyArray))
  462. for _, key := range keyArray {
  463. var keyStr string
  464. switch v := key.(type) {
  465. case string:
  466. keyStr = strings.TrimSpace(v)
  467. default:
  468. bytes, err := json.Marshal(v)
  469. if err != nil {
  470. return nil, fmt.Errorf("Vertex AI key JSON 编码失败: %w", err)
  471. }
  472. keyStr = string(bytes)
  473. }
  474. if keyStr != "" {
  475. cleanKeys = append(cleanKeys, keyStr)
  476. }
  477. }
  478. if len(cleanKeys) == 0 {
  479. return nil, fmt.Errorf("批量添加 Vertex AI 的 keys 不能为空")
  480. }
  481. return cleanKeys, nil
  482. }
  483. func AddChannel(c *gin.Context) {
  484. addChannelRequest := AddChannelRequest{}
  485. err := c.ShouldBindJSON(&addChannelRequest)
  486. if err != nil {
  487. common.ApiError(c, err)
  488. return
  489. }
  490. // 使用统一的校验函数
  491. if err := validateChannel(addChannelRequest.Channel, true); err != nil {
  492. c.JSON(http.StatusOK, gin.H{
  493. "success": false,
  494. "message": err.Error(),
  495. })
  496. return
  497. }
  498. addChannelRequest.Channel.CreatedTime = common.GetTimestamp()
  499. keys := make([]string, 0)
  500. switch addChannelRequest.Mode {
  501. case "multi_to_single":
  502. addChannelRequest.Channel.ChannelInfo.IsMultiKey = true
  503. addChannelRequest.Channel.ChannelInfo.MultiKeyMode = addChannelRequest.MultiKeyMode
  504. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi && addChannelRequest.Channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey {
  505. array, err := getVertexArrayKeys(addChannelRequest.Channel.Key)
  506. if err != nil {
  507. c.JSON(http.StatusOK, gin.H{
  508. "success": false,
  509. "message": err.Error(),
  510. })
  511. return
  512. }
  513. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(array)
  514. addChannelRequest.Channel.Key = strings.Join(array, "\n")
  515. } else {
  516. cleanKeys := make([]string, 0)
  517. for _, key := range strings.Split(addChannelRequest.Channel.Key, "\n") {
  518. if key == "" {
  519. continue
  520. }
  521. key = strings.TrimSpace(key)
  522. cleanKeys = append(cleanKeys, key)
  523. }
  524. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(cleanKeys)
  525. addChannelRequest.Channel.Key = strings.Join(cleanKeys, "\n")
  526. }
  527. keys = []string{addChannelRequest.Channel.Key}
  528. case "batch":
  529. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi && addChannelRequest.Channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey {
  530. // multi json
  531. keys, err = getVertexArrayKeys(addChannelRequest.Channel.Key)
  532. if err != nil {
  533. c.JSON(http.StatusOK, gin.H{
  534. "success": false,
  535. "message": err.Error(),
  536. })
  537. return
  538. }
  539. } else {
  540. keys = strings.Split(addChannelRequest.Channel.Key, "\n")
  541. }
  542. case "single":
  543. keys = []string{addChannelRequest.Channel.Key}
  544. default:
  545. c.JSON(http.StatusOK, gin.H{
  546. "success": false,
  547. "message": "不支持的添加模式",
  548. })
  549. return
  550. }
  551. channels := make([]model.Channel, 0, len(keys))
  552. for _, key := range keys {
  553. if key == "" {
  554. continue
  555. }
  556. localChannel := addChannelRequest.Channel
  557. localChannel.Key = key
  558. if addChannelRequest.BatchAddSetKeyPrefix2Name && len(keys) > 1 {
  559. keyPrefix := localChannel.Key
  560. if len(localChannel.Key) > 8 {
  561. keyPrefix = localChannel.Key[:8]
  562. }
  563. localChannel.Name = fmt.Sprintf("%s %s", localChannel.Name, keyPrefix)
  564. }
  565. channels = append(channels, *localChannel)
  566. }
  567. err = model.BatchInsertChannels(channels)
  568. if err != nil {
  569. common.ApiError(c, err)
  570. return
  571. }
  572. service.ResetProxyClientCache()
  573. c.JSON(http.StatusOK, gin.H{
  574. "success": true,
  575. "message": "",
  576. })
  577. return
  578. }
  579. func DeleteChannel(c *gin.Context) {
  580. id, _ := strconv.Atoi(c.Param("id"))
  581. channel := model.Channel{Id: id}
  582. err := channel.Delete()
  583. if err != nil {
  584. common.ApiError(c, err)
  585. return
  586. }
  587. model.InitChannelCache()
  588. c.JSON(http.StatusOK, gin.H{
  589. "success": true,
  590. "message": "",
  591. })
  592. return
  593. }
  594. func DeleteDisabledChannel(c *gin.Context) {
  595. rows, err := model.DeleteDisabledChannel()
  596. if err != nil {
  597. common.ApiError(c, err)
  598. return
  599. }
  600. model.InitChannelCache()
  601. c.JSON(http.StatusOK, gin.H{
  602. "success": true,
  603. "message": "",
  604. "data": rows,
  605. })
  606. return
  607. }
  608. type ChannelTag struct {
  609. Tag string `json:"tag"`
  610. NewTag *string `json:"new_tag"`
  611. Priority *int64 `json:"priority"`
  612. Weight *uint `json:"weight"`
  613. ModelMapping *string `json:"model_mapping"`
  614. Models *string `json:"models"`
  615. Groups *string `json:"groups"`
  616. ParamOverride *string `json:"param_override"`
  617. HeaderOverride *string `json:"header_override"`
  618. }
  619. func DisableTagChannels(c *gin.Context) {
  620. channelTag := ChannelTag{}
  621. err := c.ShouldBindJSON(&channelTag)
  622. if err != nil || channelTag.Tag == "" {
  623. c.JSON(http.StatusOK, gin.H{
  624. "success": false,
  625. "message": "参数错误",
  626. })
  627. return
  628. }
  629. err = model.DisableChannelByTag(channelTag.Tag)
  630. if err != nil {
  631. common.ApiError(c, err)
  632. return
  633. }
  634. model.InitChannelCache()
  635. c.JSON(http.StatusOK, gin.H{
  636. "success": true,
  637. "message": "",
  638. })
  639. return
  640. }
  641. func EnableTagChannels(c *gin.Context) {
  642. channelTag := ChannelTag{}
  643. err := c.ShouldBindJSON(&channelTag)
  644. if err != nil || channelTag.Tag == "" {
  645. c.JSON(http.StatusOK, gin.H{
  646. "success": false,
  647. "message": "参数错误",
  648. })
  649. return
  650. }
  651. err = model.EnableChannelByTag(channelTag.Tag)
  652. if err != nil {
  653. common.ApiError(c, err)
  654. return
  655. }
  656. model.InitChannelCache()
  657. c.JSON(http.StatusOK, gin.H{
  658. "success": true,
  659. "message": "",
  660. })
  661. return
  662. }
  663. func EditTagChannels(c *gin.Context) {
  664. channelTag := ChannelTag{}
  665. err := c.ShouldBindJSON(&channelTag)
  666. if err != nil {
  667. c.JSON(http.StatusOK, gin.H{
  668. "success": false,
  669. "message": "参数错误",
  670. })
  671. return
  672. }
  673. if channelTag.Tag == "" {
  674. c.JSON(http.StatusOK, gin.H{
  675. "success": false,
  676. "message": "tag不能为空",
  677. })
  678. return
  679. }
  680. if channelTag.ParamOverride != nil {
  681. trimmed := strings.TrimSpace(*channelTag.ParamOverride)
  682. if trimmed != "" && !json.Valid([]byte(trimmed)) {
  683. c.JSON(http.StatusOK, gin.H{
  684. "success": false,
  685. "message": "参数覆盖必须是合法的 JSON 格式",
  686. })
  687. return
  688. }
  689. channelTag.ParamOverride = common.GetPointer[string](trimmed)
  690. }
  691. if channelTag.HeaderOverride != nil {
  692. trimmed := strings.TrimSpace(*channelTag.HeaderOverride)
  693. if trimmed != "" && !json.Valid([]byte(trimmed)) {
  694. c.JSON(http.StatusOK, gin.H{
  695. "success": false,
  696. "message": "请求头覆盖必须是合法的 JSON 格式",
  697. })
  698. return
  699. }
  700. channelTag.HeaderOverride = common.GetPointer[string](trimmed)
  701. }
  702. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight, channelTag.ParamOverride, channelTag.HeaderOverride)
  703. if err != nil {
  704. common.ApiError(c, err)
  705. return
  706. }
  707. model.InitChannelCache()
  708. c.JSON(http.StatusOK, gin.H{
  709. "success": true,
  710. "message": "",
  711. })
  712. return
  713. }
  714. type ChannelBatch struct {
  715. Ids []int `json:"ids"`
  716. Tag *string `json:"tag"`
  717. }
  718. func DeleteChannelBatch(c *gin.Context) {
  719. channelBatch := ChannelBatch{}
  720. err := c.ShouldBindJSON(&channelBatch)
  721. if err != nil || len(channelBatch.Ids) == 0 {
  722. c.JSON(http.StatusOK, gin.H{
  723. "success": false,
  724. "message": "参数错误",
  725. })
  726. return
  727. }
  728. err = model.BatchDeleteChannels(channelBatch.Ids)
  729. if err != nil {
  730. common.ApiError(c, err)
  731. return
  732. }
  733. model.InitChannelCache()
  734. c.JSON(http.StatusOK, gin.H{
  735. "success": true,
  736. "message": "",
  737. "data": len(channelBatch.Ids),
  738. })
  739. return
  740. }
  741. type PatchChannel struct {
  742. model.Channel
  743. MultiKeyMode *string `json:"multi_key_mode"`
  744. KeyMode *string `json:"key_mode"` // 多key模式下密钥覆盖或者追加
  745. }
  746. func UpdateChannel(c *gin.Context) {
  747. channel := PatchChannel{}
  748. err := c.ShouldBindJSON(&channel)
  749. if err != nil {
  750. common.ApiError(c, err)
  751. return
  752. }
  753. // 使用统一的校验函数
  754. if err := validateChannel(&channel.Channel, false); err != nil {
  755. c.JSON(http.StatusOK, gin.H{
  756. "success": false,
  757. "message": err.Error(),
  758. })
  759. return
  760. }
  761. // Preserve existing ChannelInfo to ensure multi-key channels keep correct state even if the client does not send ChannelInfo in the request.
  762. originChannel, err := model.GetChannelById(channel.Id, true)
  763. if err != nil {
  764. c.JSON(http.StatusOK, gin.H{
  765. "success": false,
  766. "message": err.Error(),
  767. })
  768. return
  769. }
  770. // Always copy the original ChannelInfo so that fields like IsMultiKey and MultiKeySize are retained.
  771. channel.ChannelInfo = originChannel.ChannelInfo
  772. // If the request explicitly specifies a new MultiKeyMode, apply it on top of the original info.
  773. if channel.MultiKeyMode != nil && *channel.MultiKeyMode != "" {
  774. channel.ChannelInfo.MultiKeyMode = constant.MultiKeyMode(*channel.MultiKeyMode)
  775. }
  776. // 处理多key模式下的密钥追加/覆盖逻辑
  777. if channel.KeyMode != nil && channel.ChannelInfo.IsMultiKey {
  778. switch *channel.KeyMode {
  779. case "append":
  780. // 追加模式:将新密钥添加到现有密钥列表
  781. if originChannel.Key != "" {
  782. var newKeys []string
  783. var existingKeys []string
  784. // 解析现有密钥
  785. if strings.HasPrefix(strings.TrimSpace(originChannel.Key), "[") {
  786. // JSON数组格式
  787. var arr []json.RawMessage
  788. if err := json.Unmarshal([]byte(strings.TrimSpace(originChannel.Key)), &arr); err == nil {
  789. existingKeys = make([]string, len(arr))
  790. for i, v := range arr {
  791. existingKeys[i] = string(v)
  792. }
  793. }
  794. } else {
  795. // 换行分隔格式
  796. existingKeys = strings.Split(strings.Trim(originChannel.Key, "\n"), "\n")
  797. }
  798. // 处理 Vertex AI 的特殊情况
  799. if channel.Type == constant.ChannelTypeVertexAi && channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey {
  800. // 尝试解析新密钥为JSON数组
  801. if strings.HasPrefix(strings.TrimSpace(channel.Key), "[") {
  802. array, err := getVertexArrayKeys(channel.Key)
  803. if err != nil {
  804. c.JSON(http.StatusOK, gin.H{
  805. "success": false,
  806. "message": "追加密钥解析失败: " + err.Error(),
  807. })
  808. return
  809. }
  810. newKeys = array
  811. } else {
  812. // 单个JSON密钥
  813. newKeys = []string{channel.Key}
  814. }
  815. // 合并密钥
  816. allKeys := append(existingKeys, newKeys...)
  817. channel.Key = strings.Join(allKeys, "\n")
  818. } else {
  819. // 普通渠道的处理
  820. inputKeys := strings.Split(channel.Key, "\n")
  821. for _, key := range inputKeys {
  822. key = strings.TrimSpace(key)
  823. if key != "" {
  824. newKeys = append(newKeys, key)
  825. }
  826. }
  827. // 合并密钥
  828. allKeys := append(existingKeys, newKeys...)
  829. channel.Key = strings.Join(allKeys, "\n")
  830. }
  831. }
  832. case "replace":
  833. // 覆盖模式:直接使用新密钥(默认行为,不需要特殊处理)
  834. }
  835. }
  836. err = channel.Update()
  837. if err != nil {
  838. common.ApiError(c, err)
  839. return
  840. }
  841. model.InitChannelCache()
  842. service.ResetProxyClientCache()
  843. channel.Key = ""
  844. clearChannelInfo(&channel.Channel)
  845. c.JSON(http.StatusOK, gin.H{
  846. "success": true,
  847. "message": "",
  848. "data": channel,
  849. })
  850. return
  851. }
  852. func FetchModels(c *gin.Context) {
  853. var req struct {
  854. BaseURL string `json:"base_url"`
  855. Type int `json:"type"`
  856. Key string `json:"key"`
  857. }
  858. if err := c.ShouldBindJSON(&req); err != nil {
  859. c.JSON(http.StatusBadRequest, gin.H{
  860. "success": false,
  861. "message": "Invalid request",
  862. })
  863. return
  864. }
  865. baseURL := req.BaseURL
  866. if baseURL == "" {
  867. baseURL = constant.ChannelBaseURLs[req.Type]
  868. }
  869. client := &http.Client{}
  870. url := fmt.Sprintf("%s/v1/models", baseURL)
  871. request, err := http.NewRequest("GET", url, nil)
  872. if err != nil {
  873. c.JSON(http.StatusInternalServerError, gin.H{
  874. "success": false,
  875. "message": err.Error(),
  876. })
  877. return
  878. }
  879. // remove line breaks and extra spaces.
  880. key := strings.TrimSpace(req.Key)
  881. // If the key contains a line break, only take the first part.
  882. key = strings.Split(key, "\n")[0]
  883. request.Header.Set("Authorization", "Bearer "+key)
  884. response, err := client.Do(request)
  885. if err != nil {
  886. c.JSON(http.StatusInternalServerError, gin.H{
  887. "success": false,
  888. "message": err.Error(),
  889. })
  890. return
  891. }
  892. //check status code
  893. if response.StatusCode != http.StatusOK {
  894. c.JSON(http.StatusInternalServerError, gin.H{
  895. "success": false,
  896. "message": "Failed to fetch models",
  897. })
  898. return
  899. }
  900. defer response.Body.Close()
  901. var result struct {
  902. Data []struct {
  903. ID string `json:"id"`
  904. } `json:"data"`
  905. }
  906. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  907. c.JSON(http.StatusInternalServerError, gin.H{
  908. "success": false,
  909. "message": err.Error(),
  910. })
  911. return
  912. }
  913. var models []string
  914. for _, model := range result.Data {
  915. models = append(models, model.ID)
  916. }
  917. c.JSON(http.StatusOK, gin.H{
  918. "success": true,
  919. "data": models,
  920. })
  921. }
  922. func BatchSetChannelTag(c *gin.Context) {
  923. channelBatch := ChannelBatch{}
  924. err := c.ShouldBindJSON(&channelBatch)
  925. if err != nil || len(channelBatch.Ids) == 0 {
  926. c.JSON(http.StatusOK, gin.H{
  927. "success": false,
  928. "message": "参数错误",
  929. })
  930. return
  931. }
  932. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  933. if err != nil {
  934. common.ApiError(c, err)
  935. return
  936. }
  937. model.InitChannelCache()
  938. c.JSON(http.StatusOK, gin.H{
  939. "success": true,
  940. "message": "",
  941. "data": len(channelBatch.Ids),
  942. })
  943. return
  944. }
  945. func GetTagModels(c *gin.Context) {
  946. tag := c.Query("tag")
  947. if tag == "" {
  948. c.JSON(http.StatusBadRequest, gin.H{
  949. "success": false,
  950. "message": "tag不能为空",
  951. })
  952. return
  953. }
  954. channels, err := model.GetChannelsByTag(tag, false, false) // idSort=false, selectAll=false
  955. if err != nil {
  956. c.JSON(http.StatusInternalServerError, gin.H{
  957. "success": false,
  958. "message": err.Error(),
  959. })
  960. return
  961. }
  962. var longestModels string
  963. maxLength := 0
  964. // Find the longest models string among all channels with the given tag
  965. for _, channel := range channels {
  966. if channel.Models != "" {
  967. currentModels := strings.Split(channel.Models, ",")
  968. if len(currentModels) > maxLength {
  969. maxLength = len(currentModels)
  970. longestModels = channel.Models
  971. }
  972. }
  973. }
  974. c.JSON(http.StatusOK, gin.H{
  975. "success": true,
  976. "message": "",
  977. "data": longestModels,
  978. })
  979. return
  980. }
  981. // CopyChannel handles cloning an existing channel with its key.
  982. // POST /api/channel/copy/:id
  983. // Optional query params:
  984. //
  985. // suffix - string appended to the original name (default "_复制")
  986. // reset_balance - bool, when true will reset balance & used_quota to 0 (default true)
  987. func CopyChannel(c *gin.Context) {
  988. id, err := strconv.Atoi(c.Param("id"))
  989. if err != nil {
  990. c.JSON(http.StatusOK, gin.H{"success": false, "message": "invalid id"})
  991. return
  992. }
  993. suffix := c.DefaultQuery("suffix", "_复制")
  994. resetBalance := true
  995. if rbStr := c.DefaultQuery("reset_balance", "true"); rbStr != "" {
  996. if v, err := strconv.ParseBool(rbStr); err == nil {
  997. resetBalance = v
  998. }
  999. }
  1000. // fetch original channel with key
  1001. origin, err := model.GetChannelById(id, true)
  1002. if err != nil {
  1003. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  1004. return
  1005. }
  1006. // clone channel
  1007. clone := *origin // shallow copy is sufficient as we will overwrite primitives
  1008. clone.Id = 0 // let DB auto-generate
  1009. clone.CreatedTime = common.GetTimestamp()
  1010. clone.Name = origin.Name + suffix
  1011. clone.TestTime = 0
  1012. clone.ResponseTime = 0
  1013. if resetBalance {
  1014. clone.Balance = 0
  1015. clone.UsedQuota = 0
  1016. }
  1017. // insert
  1018. if err := model.BatchInsertChannels([]model.Channel{clone}); err != nil {
  1019. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  1020. return
  1021. }
  1022. model.InitChannelCache()
  1023. // success
  1024. c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": gin.H{"id": clone.Id}})
  1025. }
  1026. // MultiKeyManageRequest represents the request for multi-key management operations
  1027. type MultiKeyManageRequest struct {
  1028. ChannelId int `json:"channel_id"`
  1029. Action string `json:"action"` // "disable_key", "enable_key", "delete_key", "delete_disabled_keys", "get_key_status"
  1030. KeyIndex *int `json:"key_index,omitempty"` // for disable_key, enable_key, and delete_key actions
  1031. Page int `json:"page,omitempty"` // for get_key_status pagination
  1032. PageSize int `json:"page_size,omitempty"` // for get_key_status pagination
  1033. Status *int `json:"status,omitempty"` // for get_key_status filtering: 1=enabled, 2=manual_disabled, 3=auto_disabled, nil=all
  1034. }
  1035. // MultiKeyStatusResponse represents the response for key status query
  1036. type MultiKeyStatusResponse struct {
  1037. Keys []KeyStatus `json:"keys"`
  1038. Total int `json:"total"`
  1039. Page int `json:"page"`
  1040. PageSize int `json:"page_size"`
  1041. TotalPages int `json:"total_pages"`
  1042. // Statistics
  1043. EnabledCount int `json:"enabled_count"`
  1044. ManualDisabledCount int `json:"manual_disabled_count"`
  1045. AutoDisabledCount int `json:"auto_disabled_count"`
  1046. }
  1047. type KeyStatus struct {
  1048. Index int `json:"index"`
  1049. Status int `json:"status"` // 1: enabled, 2: disabled
  1050. DisabledTime int64 `json:"disabled_time,omitempty"`
  1051. Reason string `json:"reason,omitempty"`
  1052. KeyPreview string `json:"key_preview"` // first 10 chars of key for identification
  1053. }
  1054. // ManageMultiKeys handles multi-key management operations
  1055. func ManageMultiKeys(c *gin.Context) {
  1056. request := MultiKeyManageRequest{}
  1057. err := c.ShouldBindJSON(&request)
  1058. if err != nil {
  1059. common.ApiError(c, err)
  1060. return
  1061. }
  1062. channel, err := model.GetChannelById(request.ChannelId, true)
  1063. if err != nil {
  1064. c.JSON(http.StatusOK, gin.H{
  1065. "success": false,
  1066. "message": "渠道不存在",
  1067. })
  1068. return
  1069. }
  1070. if !channel.ChannelInfo.IsMultiKey {
  1071. c.JSON(http.StatusOK, gin.H{
  1072. "success": false,
  1073. "message": "该渠道不是多密钥模式",
  1074. })
  1075. return
  1076. }
  1077. lock := model.GetChannelPollingLock(channel.Id)
  1078. lock.Lock()
  1079. defer lock.Unlock()
  1080. switch request.Action {
  1081. case "get_key_status":
  1082. keys := channel.GetKeys()
  1083. // Default pagination parameters
  1084. page := request.Page
  1085. pageSize := request.PageSize
  1086. if page <= 0 {
  1087. page = 1
  1088. }
  1089. if pageSize <= 0 {
  1090. pageSize = 50 // Default page size
  1091. }
  1092. // Statistics for all keys (unchanged by filtering)
  1093. var enabledCount, manualDisabledCount, autoDisabledCount int
  1094. // Build all key status data first
  1095. var allKeyStatusList []KeyStatus
  1096. for i, key := range keys {
  1097. status := 1 // default enabled
  1098. var disabledTime int64
  1099. var reason string
  1100. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1101. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1102. status = s
  1103. }
  1104. }
  1105. // Count for statistics (all keys)
  1106. switch status {
  1107. case 1:
  1108. enabledCount++
  1109. case 2:
  1110. manualDisabledCount++
  1111. case 3:
  1112. autoDisabledCount++
  1113. }
  1114. if status != 1 {
  1115. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1116. disabledTime = channel.ChannelInfo.MultiKeyDisabledTime[i]
  1117. }
  1118. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1119. reason = channel.ChannelInfo.MultiKeyDisabledReason[i]
  1120. }
  1121. }
  1122. // Create key preview (first 10 chars)
  1123. keyPreview := key
  1124. if len(key) > 10 {
  1125. keyPreview = key[:10] + "..."
  1126. }
  1127. allKeyStatusList = append(allKeyStatusList, KeyStatus{
  1128. Index: i,
  1129. Status: status,
  1130. DisabledTime: disabledTime,
  1131. Reason: reason,
  1132. KeyPreview: keyPreview,
  1133. })
  1134. }
  1135. // Apply status filter if specified
  1136. var filteredKeyStatusList []KeyStatus
  1137. if request.Status != nil {
  1138. for _, keyStatus := range allKeyStatusList {
  1139. if keyStatus.Status == *request.Status {
  1140. filteredKeyStatusList = append(filteredKeyStatusList, keyStatus)
  1141. }
  1142. }
  1143. } else {
  1144. filteredKeyStatusList = allKeyStatusList
  1145. }
  1146. // Calculate pagination based on filtered results
  1147. filteredTotal := len(filteredKeyStatusList)
  1148. totalPages := (filteredTotal + pageSize - 1) / pageSize
  1149. if totalPages == 0 {
  1150. totalPages = 1
  1151. }
  1152. if page > totalPages {
  1153. page = totalPages
  1154. }
  1155. // Calculate range for current page
  1156. start := (page - 1) * pageSize
  1157. end := start + pageSize
  1158. if end > filteredTotal {
  1159. end = filteredTotal
  1160. }
  1161. // Get the page data
  1162. var pageKeyStatusList []KeyStatus
  1163. if start < filteredTotal {
  1164. pageKeyStatusList = filteredKeyStatusList[start:end]
  1165. }
  1166. c.JSON(http.StatusOK, gin.H{
  1167. "success": true,
  1168. "message": "",
  1169. "data": MultiKeyStatusResponse{
  1170. Keys: pageKeyStatusList,
  1171. Total: filteredTotal, // Total of filtered results
  1172. Page: page,
  1173. PageSize: pageSize,
  1174. TotalPages: totalPages,
  1175. EnabledCount: enabledCount, // Overall statistics
  1176. ManualDisabledCount: manualDisabledCount, // Overall statistics
  1177. AutoDisabledCount: autoDisabledCount, // Overall statistics
  1178. },
  1179. })
  1180. return
  1181. case "disable_key":
  1182. if request.KeyIndex == nil {
  1183. c.JSON(http.StatusOK, gin.H{
  1184. "success": false,
  1185. "message": "未指定要禁用的密钥索引",
  1186. })
  1187. return
  1188. }
  1189. keyIndex := *request.KeyIndex
  1190. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1191. c.JSON(http.StatusOK, gin.H{
  1192. "success": false,
  1193. "message": "密钥索引超出范围",
  1194. })
  1195. return
  1196. }
  1197. if channel.ChannelInfo.MultiKeyStatusList == nil {
  1198. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1199. }
  1200. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  1201. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1202. }
  1203. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  1204. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1205. }
  1206. channel.ChannelInfo.MultiKeyStatusList[keyIndex] = 2 // disabled
  1207. err = channel.Update()
  1208. if err != nil {
  1209. common.ApiError(c, err)
  1210. return
  1211. }
  1212. model.InitChannelCache()
  1213. c.JSON(http.StatusOK, gin.H{
  1214. "success": true,
  1215. "message": "密钥已禁用",
  1216. })
  1217. return
  1218. case "enable_key":
  1219. if request.KeyIndex == nil {
  1220. c.JSON(http.StatusOK, gin.H{
  1221. "success": false,
  1222. "message": "未指定要启用的密钥索引",
  1223. })
  1224. return
  1225. }
  1226. keyIndex := *request.KeyIndex
  1227. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1228. c.JSON(http.StatusOK, gin.H{
  1229. "success": false,
  1230. "message": "密钥索引超出范围",
  1231. })
  1232. return
  1233. }
  1234. // 从状态列表中删除该密钥的记录,使其回到默认启用状态
  1235. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1236. delete(channel.ChannelInfo.MultiKeyStatusList, keyIndex)
  1237. }
  1238. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1239. delete(channel.ChannelInfo.MultiKeyDisabledTime, keyIndex)
  1240. }
  1241. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1242. delete(channel.ChannelInfo.MultiKeyDisabledReason, keyIndex)
  1243. }
  1244. err = channel.Update()
  1245. if err != nil {
  1246. common.ApiError(c, err)
  1247. return
  1248. }
  1249. model.InitChannelCache()
  1250. c.JSON(http.StatusOK, gin.H{
  1251. "success": true,
  1252. "message": "密钥已启用",
  1253. })
  1254. return
  1255. case "enable_all_keys":
  1256. // 清空所有禁用状态,使所有密钥回到默认启用状态
  1257. var enabledCount int
  1258. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1259. enabledCount = len(channel.ChannelInfo.MultiKeyStatusList)
  1260. }
  1261. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1262. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1263. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1264. err = channel.Update()
  1265. if err != nil {
  1266. common.ApiError(c, err)
  1267. return
  1268. }
  1269. model.InitChannelCache()
  1270. c.JSON(http.StatusOK, gin.H{
  1271. "success": true,
  1272. "message": fmt.Sprintf("已启用 %d 个密钥", enabledCount),
  1273. })
  1274. return
  1275. case "disable_all_keys":
  1276. // 禁用所有启用的密钥
  1277. if channel.ChannelInfo.MultiKeyStatusList == nil {
  1278. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1279. }
  1280. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  1281. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1282. }
  1283. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  1284. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1285. }
  1286. var disabledCount int
  1287. for i := 0; i < channel.ChannelInfo.MultiKeySize; i++ {
  1288. status := 1 // default enabled
  1289. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1290. status = s
  1291. }
  1292. // 只禁用当前启用的密钥
  1293. if status == 1 {
  1294. channel.ChannelInfo.MultiKeyStatusList[i] = 2 // disabled
  1295. disabledCount++
  1296. }
  1297. }
  1298. if disabledCount == 0 {
  1299. c.JSON(http.StatusOK, gin.H{
  1300. "success": false,
  1301. "message": "没有可禁用的密钥",
  1302. })
  1303. return
  1304. }
  1305. err = channel.Update()
  1306. if err != nil {
  1307. common.ApiError(c, err)
  1308. return
  1309. }
  1310. model.InitChannelCache()
  1311. c.JSON(http.StatusOK, gin.H{
  1312. "success": true,
  1313. "message": fmt.Sprintf("已禁用 %d 个密钥", disabledCount),
  1314. })
  1315. return
  1316. case "delete_key":
  1317. if request.KeyIndex == nil {
  1318. c.JSON(http.StatusOK, gin.H{
  1319. "success": false,
  1320. "message": "未指定要删除的密钥索引",
  1321. })
  1322. return
  1323. }
  1324. keyIndex := *request.KeyIndex
  1325. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1326. c.JSON(http.StatusOK, gin.H{
  1327. "success": false,
  1328. "message": "密钥索引超出范围",
  1329. })
  1330. return
  1331. }
  1332. keys := channel.GetKeys()
  1333. var remainingKeys []string
  1334. var newStatusList = make(map[int]int)
  1335. var newDisabledTime = make(map[int]int64)
  1336. var newDisabledReason = make(map[int]string)
  1337. newIndex := 0
  1338. for i, key := range keys {
  1339. // 跳过要删除的密钥
  1340. if i == keyIndex {
  1341. continue
  1342. }
  1343. remainingKeys = append(remainingKeys, key)
  1344. // 保留其他密钥的状态信息,重新索引
  1345. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1346. if status, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists && status != 1 {
  1347. newStatusList[newIndex] = status
  1348. }
  1349. }
  1350. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1351. if t, exists := channel.ChannelInfo.MultiKeyDisabledTime[i]; exists {
  1352. newDisabledTime[newIndex] = t
  1353. }
  1354. }
  1355. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1356. if r, exists := channel.ChannelInfo.MultiKeyDisabledReason[i]; exists {
  1357. newDisabledReason[newIndex] = r
  1358. }
  1359. }
  1360. newIndex++
  1361. }
  1362. if len(remainingKeys) == 0 {
  1363. c.JSON(http.StatusOK, gin.H{
  1364. "success": false,
  1365. "message": "不能删除最后一个密钥",
  1366. })
  1367. return
  1368. }
  1369. // Update channel with remaining keys
  1370. channel.Key = strings.Join(remainingKeys, "\n")
  1371. channel.ChannelInfo.MultiKeySize = len(remainingKeys)
  1372. channel.ChannelInfo.MultiKeyStatusList = newStatusList
  1373. channel.ChannelInfo.MultiKeyDisabledTime = newDisabledTime
  1374. channel.ChannelInfo.MultiKeyDisabledReason = newDisabledReason
  1375. err = channel.Update()
  1376. if err != nil {
  1377. common.ApiError(c, err)
  1378. return
  1379. }
  1380. model.InitChannelCache()
  1381. c.JSON(http.StatusOK, gin.H{
  1382. "success": true,
  1383. "message": "密钥已删除",
  1384. })
  1385. return
  1386. case "delete_disabled_keys":
  1387. keys := channel.GetKeys()
  1388. var remainingKeys []string
  1389. var deletedCount int
  1390. var newStatusList = make(map[int]int)
  1391. var newDisabledTime = make(map[int]int64)
  1392. var newDisabledReason = make(map[int]string)
  1393. newIndex := 0
  1394. for i, key := range keys {
  1395. status := 1 // default enabled
  1396. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1397. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1398. status = s
  1399. }
  1400. }
  1401. // 只删除自动禁用(status == 3)的密钥,保留启用(status == 1)和手动禁用(status == 2)的密钥
  1402. if status == 3 {
  1403. deletedCount++
  1404. } else {
  1405. remainingKeys = append(remainingKeys, key)
  1406. // 保留非自动禁用密钥的状态信息,重新索引
  1407. if status != 1 {
  1408. newStatusList[newIndex] = status
  1409. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1410. if t, exists := channel.ChannelInfo.MultiKeyDisabledTime[i]; exists {
  1411. newDisabledTime[newIndex] = t
  1412. }
  1413. }
  1414. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1415. if r, exists := channel.ChannelInfo.MultiKeyDisabledReason[i]; exists {
  1416. newDisabledReason[newIndex] = r
  1417. }
  1418. }
  1419. }
  1420. newIndex++
  1421. }
  1422. }
  1423. if deletedCount == 0 {
  1424. c.JSON(http.StatusOK, gin.H{
  1425. "success": false,
  1426. "message": "没有需要删除的自动禁用密钥",
  1427. })
  1428. return
  1429. }
  1430. // Update channel with remaining keys
  1431. channel.Key = strings.Join(remainingKeys, "\n")
  1432. channel.ChannelInfo.MultiKeySize = len(remainingKeys)
  1433. channel.ChannelInfo.MultiKeyStatusList = newStatusList
  1434. channel.ChannelInfo.MultiKeyDisabledTime = newDisabledTime
  1435. channel.ChannelInfo.MultiKeyDisabledReason = newDisabledReason
  1436. err = channel.Update()
  1437. if err != nil {
  1438. common.ApiError(c, err)
  1439. return
  1440. }
  1441. model.InitChannelCache()
  1442. c.JSON(http.StatusOK, gin.H{
  1443. "success": true,
  1444. "message": fmt.Sprintf("已删除 %d 个自动禁用的密钥", deletedCount),
  1445. "data": deletedCount,
  1446. })
  1447. return
  1448. default:
  1449. c.JSON(http.StatusOK, gin.H{
  1450. "success": false,
  1451. "message": "不支持的操作",
  1452. })
  1453. return
  1454. }
  1455. }