channel.go 40 KB

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