channel.go 40 KB

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