25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

2129 satır
54 KiB

  1. package controller
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/constant"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/model"
  14. "github.com/QuantumNous/new-api/relay/channel/gemini"
  15. "github.com/QuantumNous/new-api/relay/channel/ollama"
  16. "github.com/QuantumNous/new-api/service"
  17. "github.com/gin-gonic/gin"
  18. )
  19. type OpenAIModel struct {
  20. ID string `json:"id"`
  21. Object string `json:"object"`
  22. Created int64 `json:"created"`
  23. OwnedBy string `json:"owned_by"`
  24. Metadata map[string]any `json:"metadata,omitempty"`
  25. Permission []struct {
  26. ID string `json:"id"`
  27. Object string `json:"object"`
  28. Created int64 `json:"created"`
  29. AllowCreateEngine bool `json:"allow_create_engine"`
  30. AllowSampling bool `json:"allow_sampling"`
  31. AllowLogprobs bool `json:"allow_logprobs"`
  32. AllowSearchIndices bool `json:"allow_search_indices"`
  33. AllowView bool `json:"allow_view"`
  34. AllowFineTuning bool `json:"allow_fine_tuning"`
  35. Organization string `json:"organization"`
  36. Group string `json:"group"`
  37. IsBlocking bool `json:"is_blocking"`
  38. } `json:"permission"`
  39. Root string `json:"root"`
  40. Parent string `json:"parent"`
  41. }
  42. type OpenAIModelsResponse struct {
  43. Data []OpenAIModel `json:"data"`
  44. Success bool `json:"success"`
  45. }
  46. func parseStatusFilter(statusParam string) int {
  47. switch strings.ToLower(statusParam) {
  48. case "enabled", "1":
  49. return common.ChannelStatusEnabled
  50. case "disabled", "0":
  51. return 0
  52. default:
  53. return -1
  54. }
  55. }
  56. func clearChannelInfo(channel *model.Channel) {
  57. if channel.ChannelInfo.IsMultiKey {
  58. channel.ChannelInfo.MultiKeyDisabledReason = nil
  59. channel.ChannelInfo.MultiKeyDisabledTime = nil
  60. }
  61. }
  62. func GetAllChannels(c *gin.Context) {
  63. pageInfo := common.GetPageQuery(c)
  64. channelData := make([]*model.Channel, 0)
  65. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  66. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  67. statusParam := c.Query("status")
  68. // statusFilter: -1 all, 1 enabled, 0 disabled (include auto & manual)
  69. statusFilter := parseStatusFilter(statusParam)
  70. // type filter
  71. typeStr := c.Query("type")
  72. typeFilter := -1
  73. if typeStr != "" {
  74. if t, err := strconv.Atoi(typeStr); err == nil {
  75. typeFilter = t
  76. }
  77. }
  78. var total int64
  79. if enableTagMode {
  80. tags, err := model.GetPaginatedTags(pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  81. if err != nil {
  82. common.SysError("failed to get paginated tags: " + err.Error())
  83. c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取标签失败,请稍后重试"})
  84. return
  85. }
  86. for _, tag := range tags {
  87. if tag == nil || *tag == "" {
  88. continue
  89. }
  90. tagChannels, err := model.GetChannelsByTag(*tag, idSort, false)
  91. if err != nil {
  92. continue
  93. }
  94. filtered := make([]*model.Channel, 0)
  95. for _, ch := range tagChannels {
  96. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  97. continue
  98. }
  99. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  100. continue
  101. }
  102. if typeFilter >= 0 && ch.Type != typeFilter {
  103. continue
  104. }
  105. filtered = append(filtered, ch)
  106. }
  107. channelData = append(channelData, filtered...)
  108. }
  109. total, _ = model.CountAllTags()
  110. } else {
  111. baseQuery := model.DB.Model(&model.Channel{})
  112. if typeFilter >= 0 {
  113. baseQuery = baseQuery.Where("type = ?", typeFilter)
  114. }
  115. if statusFilter == common.ChannelStatusEnabled {
  116. baseQuery = baseQuery.Where("status = ?", common.ChannelStatusEnabled)
  117. } else if statusFilter == 0 {
  118. baseQuery = baseQuery.Where("status != ?", common.ChannelStatusEnabled)
  119. }
  120. baseQuery.Count(&total)
  121. order := "priority desc"
  122. if idSort {
  123. order = "id desc"
  124. }
  125. err := baseQuery.Order(order).Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("key").Find(&channelData).Error
  126. if err != nil {
  127. common.SysError("failed to get channels: " + err.Error())
  128. c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取渠道列表失败,请稍后重试"})
  129. return
  130. }
  131. }
  132. for _, datum := range channelData {
  133. clearChannelInfo(datum)
  134. }
  135. countQuery := model.DB.Model(&model.Channel{})
  136. if statusFilter == common.ChannelStatusEnabled {
  137. countQuery = countQuery.Where("status = ?", common.ChannelStatusEnabled)
  138. } else if statusFilter == 0 {
  139. countQuery = countQuery.Where("status != ?", common.ChannelStatusEnabled)
  140. }
  141. var results []struct {
  142. Type int64
  143. Count int64
  144. }
  145. _ = countQuery.Select("type, count(*) as count").Group("type").Find(&results).Error
  146. typeCounts := make(map[int64]int64)
  147. for _, r := range results {
  148. typeCounts[r.Type] = r.Count
  149. }
  150. common.ApiSuccess(c, gin.H{
  151. "items": channelData,
  152. "total": total,
  153. "page": pageInfo.GetPage(),
  154. "page_size": pageInfo.GetPageSize(),
  155. "type_counts": typeCounts,
  156. })
  157. return
  158. }
  159. func buildFetchModelsHeaders(channel *model.Channel, key string) (http.Header, error) {
  160. var headers http.Header
  161. switch channel.Type {
  162. case constant.ChannelTypeAnthropic:
  163. headers = GetClaudeAuthHeader(key)
  164. default:
  165. headers = GetAuthHeader(key)
  166. }
  167. headerOverride := channel.GetHeaderOverride()
  168. for k, v := range headerOverride {
  169. str, ok := v.(string)
  170. if !ok {
  171. return nil, fmt.Errorf("invalid header override for key %s", k)
  172. }
  173. if strings.Contains(str, "{api_key}") {
  174. str = strings.ReplaceAll(str, "{api_key}", key)
  175. }
  176. headers.Set(k, str)
  177. }
  178. return headers, nil
  179. }
  180. func FetchUpstreamModels(c *gin.Context) {
  181. id, err := strconv.Atoi(c.Param("id"))
  182. if err != nil {
  183. common.ApiError(c, err)
  184. return
  185. }
  186. channel, err := model.GetChannelById(id, true)
  187. if err != nil {
  188. common.ApiError(c, err)
  189. return
  190. }
  191. baseURL := constant.ChannelBaseURLs[channel.Type]
  192. if channel.GetBaseURL() != "" {
  193. baseURL = channel.GetBaseURL()
  194. }
  195. // 对于 Ollama 渠道,使用特殊处理
  196. if channel.Type == constant.ChannelTypeOllama {
  197. key := strings.Split(channel.Key, "\n")[0]
  198. models, err := ollama.FetchOllamaModels(baseURL, key)
  199. if err != nil {
  200. c.JSON(http.StatusOK, gin.H{
  201. "success": false,
  202. "message": fmt.Sprintf("获取Ollama模型失败: %s", err.Error()),
  203. })
  204. return
  205. }
  206. result := OpenAIModelsResponse{
  207. Data: make([]OpenAIModel, 0, len(models)),
  208. }
  209. for _, modelInfo := range models {
  210. metadata := map[string]any{}
  211. if modelInfo.Size > 0 {
  212. metadata["size"] = modelInfo.Size
  213. }
  214. if modelInfo.Digest != "" {
  215. metadata["digest"] = modelInfo.Digest
  216. }
  217. if modelInfo.ModifiedAt != "" {
  218. metadata["modified_at"] = modelInfo.ModifiedAt
  219. }
  220. details := modelInfo.Details
  221. if details.ParentModel != "" || details.Format != "" || details.Family != "" || len(details.Families) > 0 || details.ParameterSize != "" || details.QuantizationLevel != "" {
  222. metadata["details"] = modelInfo.Details
  223. }
  224. if len(metadata) == 0 {
  225. metadata = nil
  226. }
  227. result.Data = append(result.Data, OpenAIModel{
  228. ID: modelInfo.Name,
  229. Object: "model",
  230. Created: 0,
  231. OwnedBy: "ollama",
  232. Metadata: metadata,
  233. })
  234. }
  235. c.JSON(http.StatusOK, gin.H{
  236. "success": true,
  237. "data": result.Data,
  238. })
  239. return
  240. }
  241. // 对于 Gemini 渠道,使用特殊处理
  242. if channel.Type == constant.ChannelTypeGemini {
  243. // 获取用于请求的可用密钥(多密钥渠道优先使用启用状态的密钥)
  244. key, _, apiErr := channel.GetNextEnabledKey()
  245. if apiErr != nil {
  246. c.JSON(http.StatusOK, gin.H{
  247. "success": false,
  248. "message": fmt.Sprintf("获取渠道密钥失败: %s", apiErr.Error()),
  249. })
  250. return
  251. }
  252. key = strings.TrimSpace(key)
  253. models, err := gemini.FetchGeminiModels(baseURL, key, channel.GetSetting().Proxy)
  254. if err != nil {
  255. c.JSON(http.StatusOK, gin.H{
  256. "success": false,
  257. "message": fmt.Sprintf("获取Gemini模型失败: %s", err.Error()),
  258. })
  259. return
  260. }
  261. c.JSON(http.StatusOK, gin.H{
  262. "success": true,
  263. "message": "",
  264. "data": models,
  265. })
  266. return
  267. }
  268. var url string
  269. switch channel.Type {
  270. case constant.ChannelTypeAli:
  271. url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
  272. case constant.ChannelTypeZhipu_v4:
  273. if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
  274. url = fmt.Sprintf("%s/models", plan.OpenAIBaseURL)
  275. } else {
  276. url = fmt.Sprintf("%s/api/paas/v4/models", baseURL)
  277. }
  278. case constant.ChannelTypeVolcEngine:
  279. if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
  280. url = fmt.Sprintf("%s/v1/models", plan.OpenAIBaseURL)
  281. } else {
  282. url = fmt.Sprintf("%s/v1/models", baseURL)
  283. }
  284. case constant.ChannelTypeMoonshot:
  285. if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
  286. url = fmt.Sprintf("%s/models", plan.OpenAIBaseURL)
  287. } else {
  288. url = fmt.Sprintf("%s/v1/models", baseURL)
  289. }
  290. default:
  291. url = fmt.Sprintf("%s/v1/models", baseURL)
  292. }
  293. // 获取用于请求的可用密钥(多密钥渠道优先使用启用状态的密钥)
  294. key, _, apiErr := channel.GetNextEnabledKey()
  295. if apiErr != nil {
  296. c.JSON(http.StatusOK, gin.H{
  297. "success": false,
  298. "message": fmt.Sprintf("获取渠道密钥失败: %s", apiErr.Error()),
  299. })
  300. return
  301. }
  302. key = strings.TrimSpace(key)
  303. headers, err := buildFetchModelsHeaders(channel, key)
  304. if err != nil {
  305. common.ApiError(c, err)
  306. return
  307. }
  308. body, err := GetResponseBody("GET", url, channel, headers)
  309. if err != nil {
  310. common.ApiError(c, err)
  311. return
  312. }
  313. var result OpenAIModelsResponse
  314. if err = json.Unmarshal(body, &result); err != nil {
  315. c.JSON(http.StatusOK, gin.H{
  316. "success": false,
  317. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  318. })
  319. return
  320. }
  321. var ids []string
  322. for _, model := range result.Data {
  323. id := model.ID
  324. if channel.Type == constant.ChannelTypeGemini {
  325. id = strings.TrimPrefix(id, "models/")
  326. }
  327. ids = append(ids, id)
  328. }
  329. c.JSON(http.StatusOK, gin.H{
  330. "success": true,
  331. "message": "",
  332. "data": ids,
  333. })
  334. }
  335. func FixChannelsAbilities(c *gin.Context) {
  336. success, fails, err := model.FixAbility()
  337. if err != nil {
  338. common.ApiError(c, err)
  339. return
  340. }
  341. c.JSON(http.StatusOK, gin.H{
  342. "success": true,
  343. "message": "",
  344. "data": gin.H{
  345. "success": success,
  346. "fails": fails,
  347. },
  348. })
  349. }
  350. func SearchChannels(c *gin.Context) {
  351. keyword := c.Query("keyword")
  352. group := c.Query("group")
  353. modelKeyword := c.Query("model")
  354. statusParam := c.Query("status")
  355. statusFilter := parseStatusFilter(statusParam)
  356. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  357. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  358. channelData := make([]*model.Channel, 0)
  359. if enableTagMode {
  360. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  361. if err != nil {
  362. c.JSON(http.StatusOK, gin.H{
  363. "success": false,
  364. "message": err.Error(),
  365. })
  366. return
  367. }
  368. for _, tag := range tags {
  369. if tag != nil && *tag != "" {
  370. tagChannel, err := model.GetChannelsByTag(*tag, idSort, false)
  371. if err == nil {
  372. channelData = append(channelData, tagChannel...)
  373. }
  374. }
  375. }
  376. } else {
  377. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  378. if err != nil {
  379. c.JSON(http.StatusOK, gin.H{
  380. "success": false,
  381. "message": err.Error(),
  382. })
  383. return
  384. }
  385. channelData = channels
  386. }
  387. if statusFilter == common.ChannelStatusEnabled || statusFilter == 0 {
  388. filtered := make([]*model.Channel, 0, len(channelData))
  389. for _, ch := range channelData {
  390. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  391. continue
  392. }
  393. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  394. continue
  395. }
  396. filtered = append(filtered, ch)
  397. }
  398. channelData = filtered
  399. }
  400. // calculate type counts for search results
  401. typeCounts := make(map[int64]int64)
  402. for _, channel := range channelData {
  403. typeCounts[int64(channel.Type)]++
  404. }
  405. typeParam := c.Query("type")
  406. typeFilter := -1
  407. if typeParam != "" {
  408. if tp, err := strconv.Atoi(typeParam); err == nil {
  409. typeFilter = tp
  410. }
  411. }
  412. if typeFilter >= 0 {
  413. filtered := make([]*model.Channel, 0, len(channelData))
  414. for _, ch := range channelData {
  415. if ch.Type == typeFilter {
  416. filtered = append(filtered, ch)
  417. }
  418. }
  419. channelData = filtered
  420. }
  421. page, _ := strconv.Atoi(c.DefaultQuery("p", "1"))
  422. pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
  423. if page < 1 {
  424. page = 1
  425. }
  426. if pageSize <= 0 {
  427. pageSize = 20
  428. }
  429. total := len(channelData)
  430. startIdx := (page - 1) * pageSize
  431. if startIdx > total {
  432. startIdx = total
  433. }
  434. endIdx := startIdx + pageSize
  435. if endIdx > total {
  436. endIdx = total
  437. }
  438. pagedData := channelData[startIdx:endIdx]
  439. for _, datum := range pagedData {
  440. clearChannelInfo(datum)
  441. }
  442. c.JSON(http.StatusOK, gin.H{
  443. "success": true,
  444. "message": "",
  445. "data": gin.H{
  446. "items": pagedData,
  447. "total": total,
  448. "type_counts": typeCounts,
  449. },
  450. })
  451. return
  452. }
  453. func GetChannel(c *gin.Context) {
  454. id, err := strconv.Atoi(c.Param("id"))
  455. if err != nil {
  456. common.ApiError(c, err)
  457. return
  458. }
  459. channel, err := model.GetChannelById(id, false)
  460. if err != nil {
  461. common.ApiError(c, err)
  462. return
  463. }
  464. if channel != nil {
  465. clearChannelInfo(channel)
  466. }
  467. c.JSON(http.StatusOK, gin.H{
  468. "success": true,
  469. "message": "",
  470. "data": channel,
  471. })
  472. return
  473. }
  474. // GetChannelKey 获取渠道密钥(需要通过安全验证中间件)
  475. // 此函数依赖 SecureVerificationRequired 中间件,确保用户已通过安全验证
  476. func GetChannelKey(c *gin.Context) {
  477. userId := c.GetInt("id")
  478. channelId, err := strconv.Atoi(c.Param("id"))
  479. if err != nil {
  480. common.ApiError(c, fmt.Errorf("渠道ID格式错误: %v", err))
  481. return
  482. }
  483. // 获取渠道信息(包含密钥)
  484. channel, err := model.GetChannelById(channelId, true)
  485. if err != nil {
  486. common.ApiError(c, fmt.Errorf("获取渠道信息失败: %v", err))
  487. return
  488. }
  489. if channel == nil {
  490. common.ApiError(c, fmt.Errorf("渠道不存在"))
  491. return
  492. }
  493. // 记录操作日志
  494. model.RecordLog(userId, model.LogTypeSystem, fmt.Sprintf("查看渠道密钥信息 (渠道ID: %d)", channelId))
  495. // 返回渠道密钥
  496. c.JSON(http.StatusOK, gin.H{
  497. "success": true,
  498. "message": "获取成功",
  499. "data": map[string]interface{}{
  500. "key": channel.Key,
  501. },
  502. })
  503. }
  504. // validateTwoFactorAuth 统一的2FA验证函数
  505. func validateTwoFactorAuth(twoFA *model.TwoFA, code string) bool {
  506. // 尝试验证TOTP
  507. if cleanCode, err := common.ValidateNumericCode(code); err == nil {
  508. if isValid, _ := twoFA.ValidateTOTPAndUpdateUsage(cleanCode); isValid {
  509. return true
  510. }
  511. }
  512. // 尝试验证备用码
  513. if isValid, err := twoFA.ValidateBackupCodeAndUpdateUsage(code); err == nil && isValid {
  514. return true
  515. }
  516. return false
  517. }
  518. // validateChannel 通用的渠道校验函数
  519. func validateChannel(channel *model.Channel, isAdd bool) error {
  520. // 校验 channel settings
  521. if err := channel.ValidateSettings(); err != nil {
  522. return fmt.Errorf("渠道额外设置[channel setting] 格式错误:%s", err.Error())
  523. }
  524. // 如果是添加操作,检查 channel 和 key 是否为空
  525. if isAdd {
  526. if channel == nil || channel.Key == "" {
  527. return fmt.Errorf("channel cannot be empty")
  528. }
  529. if strings.TrimSpace(channel.PublicName) == "" {
  530. return fmt.Errorf("public name cannot be empty")
  531. }
  532. // 检查模型名称长度是否超过 255
  533. for _, m := range channel.GetModels() {
  534. if len(m) > 255 {
  535. return fmt.Errorf("模型名称过长: %s", m)
  536. }
  537. }
  538. }
  539. // VertexAI 特殊校验
  540. if channel.Type == constant.ChannelTypeVertexAi {
  541. if channel.Other == "" {
  542. return fmt.Errorf("部署地区不能为空")
  543. }
  544. regionMap, err := common.StrToMap(channel.Other)
  545. if err != nil {
  546. return fmt.Errorf("部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}")
  547. }
  548. if regionMap["default"] == nil {
  549. return fmt.Errorf("部署地区必须包含default字段")
  550. }
  551. }
  552. // Codex OAuth key validation (optional, only when JSON object is provided)
  553. if channel.Type == constant.ChannelTypeCodex {
  554. trimmedKey := strings.TrimSpace(channel.Key)
  555. if isAdd || trimmedKey != "" {
  556. if !strings.HasPrefix(trimmedKey, "{") {
  557. return fmt.Errorf("Codex key must be a valid JSON object")
  558. }
  559. var keyMap map[string]any
  560. if err := common.Unmarshal([]byte(trimmedKey), &keyMap); err != nil {
  561. return fmt.Errorf("Codex key must be a valid JSON object")
  562. }
  563. if v, ok := keyMap["access_token"]; !ok || v == nil || strings.TrimSpace(fmt.Sprintf("%v", v)) == "" {
  564. return fmt.Errorf("Codex key JSON must include access_token")
  565. }
  566. if v, ok := keyMap["account_id"]; !ok || v == nil || strings.TrimSpace(fmt.Sprintf("%v", v)) == "" {
  567. return fmt.Errorf("Codex key JSON must include account_id")
  568. }
  569. }
  570. }
  571. return nil
  572. }
  573. func RefreshCodexChannelCredential(c *gin.Context) {
  574. channelId, err := strconv.Atoi(c.Param("id"))
  575. if err != nil {
  576. common.ApiError(c, fmt.Errorf("invalid channel id: %w", err))
  577. return
  578. }
  579. ctx, cancel := context.WithTimeout(c.Request.Context(), 10*time.Second)
  580. defer cancel()
  581. oauthKey, ch, err := service.RefreshCodexChannelCredential(ctx, channelId, service.CodexCredentialRefreshOptions{ResetCaches: true})
  582. if err != nil {
  583. common.SysError("failed to refresh codex channel credential: " + err.Error())
  584. c.JSON(http.StatusOK, gin.H{"success": false, "message": "刷新凭证失败,请稍后重试"})
  585. return
  586. }
  587. c.JSON(http.StatusOK, gin.H{
  588. "success": true,
  589. "message": "refreshed",
  590. "data": gin.H{
  591. "expires_at": oauthKey.Expired,
  592. "last_refresh": oauthKey.LastRefresh,
  593. "account_id": oauthKey.AccountID,
  594. "email": oauthKey.Email,
  595. "channel_id": ch.Id,
  596. "channel_type": ch.Type,
  597. "channel_name": ch.Name,
  598. },
  599. })
  600. }
  601. type AddChannelRequest struct {
  602. Mode string `json:"mode"`
  603. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  604. BatchAddSetKeyPrefix2Name bool `json:"batch_add_set_key_prefix_2_name"`
  605. Channel *model.Channel `json:"channel"`
  606. }
  607. func getVertexArrayKeys(keys string) ([]string, error) {
  608. if keys == "" {
  609. return nil, nil
  610. }
  611. var keyArray []interface{}
  612. err := common.Unmarshal([]byte(keys), &keyArray)
  613. if err != nil {
  614. return nil, fmt.Errorf("批量添加 Vertex AI 必须使用标准的JsonArray格式,例如[{key1}, {key2}...],请检查输入: %w", err)
  615. }
  616. cleanKeys := make([]string, 0, len(keyArray))
  617. for _, key := range keyArray {
  618. var keyStr string
  619. switch v := key.(type) {
  620. case string:
  621. keyStr = strings.TrimSpace(v)
  622. default:
  623. bytes, err := json.Marshal(v)
  624. if err != nil {
  625. return nil, fmt.Errorf("Vertex AI key JSON 编码失败: %w", err)
  626. }
  627. keyStr = string(bytes)
  628. }
  629. if keyStr != "" {
  630. cleanKeys = append(cleanKeys, keyStr)
  631. }
  632. }
  633. if len(cleanKeys) == 0 {
  634. return nil, fmt.Errorf("批量添加 Vertex AI 的 keys 不能为空")
  635. }
  636. return cleanKeys, nil
  637. }
  638. func AddChannel(c *gin.Context) {
  639. addChannelRequest := AddChannelRequest{}
  640. err := c.ShouldBindJSON(&addChannelRequest)
  641. if err != nil {
  642. common.ApiError(c, err)
  643. return
  644. }
  645. // 使用统一的校验函数
  646. if err := validateChannel(addChannelRequest.Channel, true); err != nil {
  647. c.JSON(http.StatusOK, gin.H{
  648. "success": false,
  649. "message": err.Error(),
  650. })
  651. return
  652. }
  653. addChannelRequest.Channel.CreatedTime = common.GetTimestamp()
  654. keys := make([]string, 0)
  655. switch addChannelRequest.Mode {
  656. case "multi_to_single":
  657. addChannelRequest.Channel.ChannelInfo.IsMultiKey = true
  658. addChannelRequest.Channel.ChannelInfo.MultiKeyMode = addChannelRequest.MultiKeyMode
  659. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi && addChannelRequest.Channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey {
  660. array, err := getVertexArrayKeys(addChannelRequest.Channel.Key)
  661. if err != nil {
  662. c.JSON(http.StatusOK, gin.H{
  663. "success": false,
  664. "message": err.Error(),
  665. })
  666. return
  667. }
  668. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(array)
  669. addChannelRequest.Channel.Key = strings.Join(array, "\n")
  670. } else {
  671. cleanKeys := make([]string, 0)
  672. for _, key := range strings.Split(addChannelRequest.Channel.Key, "\n") {
  673. if key == "" {
  674. continue
  675. }
  676. key = strings.TrimSpace(key)
  677. cleanKeys = append(cleanKeys, key)
  678. }
  679. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(cleanKeys)
  680. addChannelRequest.Channel.Key = strings.Join(cleanKeys, "\n")
  681. }
  682. keys = []string{addChannelRequest.Channel.Key}
  683. case "batch":
  684. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi && addChannelRequest.Channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey {
  685. // multi json
  686. keys, err = getVertexArrayKeys(addChannelRequest.Channel.Key)
  687. if err != nil {
  688. c.JSON(http.StatusOK, gin.H{
  689. "success": false,
  690. "message": err.Error(),
  691. })
  692. return
  693. }
  694. } else {
  695. keys = strings.Split(addChannelRequest.Channel.Key, "\n")
  696. }
  697. case "single":
  698. keys = []string{addChannelRequest.Channel.Key}
  699. default:
  700. c.JSON(http.StatusOK, gin.H{
  701. "success": false,
  702. "message": "不支持的添加模式",
  703. })
  704. return
  705. }
  706. channels := make([]model.Channel, 0, len(keys))
  707. for _, key := range keys {
  708. if key == "" {
  709. continue
  710. }
  711. localChannel := addChannelRequest.Channel
  712. localChannel.Key = key
  713. if addChannelRequest.BatchAddSetKeyPrefix2Name && len(keys) > 1 {
  714. keyPrefix := localChannel.Key
  715. if len(localChannel.Key) > 8 {
  716. keyPrefix = localChannel.Key[:8]
  717. }
  718. localChannel.Name = fmt.Sprintf("%s %s", localChannel.Name, keyPrefix)
  719. }
  720. channels = append(channels, *localChannel)
  721. }
  722. err = model.BatchInsertChannels(channels)
  723. if err != nil {
  724. common.ApiError(c, err)
  725. return
  726. }
  727. service.ResetProxyClientCache()
  728. c.JSON(http.StatusOK, gin.H{
  729. "success": true,
  730. "message": "",
  731. })
  732. return
  733. }
  734. func DeleteChannel(c *gin.Context) {
  735. id, _ := strconv.Atoi(c.Param("id"))
  736. channel := model.Channel{Id: id}
  737. err := channel.Delete()
  738. if err != nil {
  739. common.ApiError(c, err)
  740. return
  741. }
  742. model.InitChannelCache()
  743. c.JSON(http.StatusOK, gin.H{
  744. "success": true,
  745. "message": "",
  746. })
  747. return
  748. }
  749. func DeleteDisabledChannel(c *gin.Context) {
  750. rows, err := model.DeleteDisabledChannel()
  751. if err != nil {
  752. common.ApiError(c, err)
  753. return
  754. }
  755. model.InitChannelCache()
  756. c.JSON(http.StatusOK, gin.H{
  757. "success": true,
  758. "message": "",
  759. "data": rows,
  760. })
  761. return
  762. }
  763. type ChannelTag struct {
  764. Tag string `json:"tag"`
  765. NewTag *string `json:"new_tag"`
  766. Priority *int64 `json:"priority"`
  767. Weight *uint `json:"weight"`
  768. ModelMapping *string `json:"model_mapping"`
  769. Models *string `json:"models"`
  770. Groups *string `json:"groups"`
  771. ParamOverride *string `json:"param_override"`
  772. HeaderOverride *string `json:"header_override"`
  773. }
  774. func DisableTagChannels(c *gin.Context) {
  775. channelTag := ChannelTag{}
  776. err := c.ShouldBindJSON(&channelTag)
  777. if err != nil || channelTag.Tag == "" {
  778. c.JSON(http.StatusOK, gin.H{
  779. "success": false,
  780. "message": "参数错误",
  781. })
  782. return
  783. }
  784. err = model.DisableChannelByTag(channelTag.Tag)
  785. if err != nil {
  786. common.ApiError(c, err)
  787. return
  788. }
  789. model.InitChannelCache()
  790. c.JSON(http.StatusOK, gin.H{
  791. "success": true,
  792. "message": "",
  793. })
  794. return
  795. }
  796. func EnableTagChannels(c *gin.Context) {
  797. channelTag := ChannelTag{}
  798. err := c.ShouldBindJSON(&channelTag)
  799. if err != nil || channelTag.Tag == "" {
  800. c.JSON(http.StatusOK, gin.H{
  801. "success": false,
  802. "message": "参数错误",
  803. })
  804. return
  805. }
  806. err = model.EnableChannelByTag(channelTag.Tag)
  807. if err != nil {
  808. common.ApiError(c, err)
  809. return
  810. }
  811. model.InitChannelCache()
  812. c.JSON(http.StatusOK, gin.H{
  813. "success": true,
  814. "message": "",
  815. })
  816. return
  817. }
  818. func EditTagChannels(c *gin.Context) {
  819. channelTag := ChannelTag{}
  820. err := c.ShouldBindJSON(&channelTag)
  821. if err != nil {
  822. c.JSON(http.StatusOK, gin.H{
  823. "success": false,
  824. "message": "参数错误",
  825. })
  826. return
  827. }
  828. if channelTag.Tag == "" {
  829. c.JSON(http.StatusOK, gin.H{
  830. "success": false,
  831. "message": "tag不能为空",
  832. })
  833. return
  834. }
  835. if channelTag.ParamOverride != nil {
  836. trimmed := strings.TrimSpace(*channelTag.ParamOverride)
  837. if trimmed != "" && !json.Valid([]byte(trimmed)) {
  838. c.JSON(http.StatusOK, gin.H{
  839. "success": false,
  840. "message": "参数覆盖必须是合法的 JSON 格式",
  841. })
  842. return
  843. }
  844. channelTag.ParamOverride = common.GetPointer[string](trimmed)
  845. }
  846. if channelTag.HeaderOverride != nil {
  847. trimmed := strings.TrimSpace(*channelTag.HeaderOverride)
  848. if trimmed != "" && !json.Valid([]byte(trimmed)) {
  849. c.JSON(http.StatusOK, gin.H{
  850. "success": false,
  851. "message": "请求头覆盖必须是合法的 JSON 格式",
  852. })
  853. return
  854. }
  855. channelTag.HeaderOverride = common.GetPointer[string](trimmed)
  856. }
  857. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight, channelTag.ParamOverride, channelTag.HeaderOverride)
  858. if err != nil {
  859. common.ApiError(c, err)
  860. return
  861. }
  862. model.InitChannelCache()
  863. c.JSON(http.StatusOK, gin.H{
  864. "success": true,
  865. "message": "",
  866. })
  867. return
  868. }
  869. type ChannelBatch struct {
  870. Ids []int `json:"ids"`
  871. Tag *string `json:"tag"`
  872. }
  873. func DeleteChannelBatch(c *gin.Context) {
  874. channelBatch := ChannelBatch{}
  875. err := c.ShouldBindJSON(&channelBatch)
  876. if err != nil || len(channelBatch.Ids) == 0 {
  877. c.JSON(http.StatusOK, gin.H{
  878. "success": false,
  879. "message": "参数错误",
  880. })
  881. return
  882. }
  883. err = model.BatchDeleteChannels(channelBatch.Ids)
  884. if err != nil {
  885. common.ApiError(c, err)
  886. return
  887. }
  888. model.InitChannelCache()
  889. c.JSON(http.StatusOK, gin.H{
  890. "success": true,
  891. "message": "",
  892. "data": len(channelBatch.Ids),
  893. })
  894. return
  895. }
  896. type PatchChannel struct {
  897. model.Channel
  898. MultiKeyMode *string `json:"multi_key_mode"`
  899. KeyMode *string `json:"key_mode"` // 多key模式下密钥覆盖或者追加
  900. }
  901. func UpdateChannel(c *gin.Context) {
  902. channel := PatchChannel{}
  903. err := c.ShouldBindJSON(&channel)
  904. if err != nil {
  905. common.ApiError(c, err)
  906. return
  907. }
  908. // 使用统一的校验函数
  909. if err := validateChannel(&channel.Channel, false); err != nil {
  910. c.JSON(http.StatusOK, gin.H{
  911. "success": false,
  912. "message": err.Error(),
  913. })
  914. return
  915. }
  916. // Preserve existing ChannelInfo to ensure multi-key channels keep correct state even if the client does not send ChannelInfo in the request.
  917. originChannel, err := model.GetChannelById(channel.Id, true)
  918. if err != nil {
  919. c.JSON(http.StatusOK, gin.H{
  920. "success": false,
  921. "message": err.Error(),
  922. })
  923. return
  924. }
  925. // Always copy the original ChannelInfo so that fields like IsMultiKey and MultiKeySize are retained.
  926. channel.ChannelInfo = originChannel.ChannelInfo
  927. // If the request explicitly specifies a new MultiKeyMode, apply it on top of the original info.
  928. if channel.MultiKeyMode != nil && *channel.MultiKeyMode != "" {
  929. channel.ChannelInfo.MultiKeyMode = constant.MultiKeyMode(*channel.MultiKeyMode)
  930. }
  931. // 处理多key模式下的密钥追加/覆盖逻辑
  932. if channel.KeyMode != nil && channel.ChannelInfo.IsMultiKey {
  933. switch *channel.KeyMode {
  934. case "append":
  935. // 追加模式:将新密钥添加到现有密钥列表
  936. if originChannel.Key != "" {
  937. var newKeys []string
  938. var existingKeys []string
  939. // 解析现有密钥
  940. if strings.HasPrefix(strings.TrimSpace(originChannel.Key), "[") {
  941. // JSON数组格式
  942. var arr []json.RawMessage
  943. if err := json.Unmarshal([]byte(strings.TrimSpace(originChannel.Key)), &arr); err == nil {
  944. existingKeys = make([]string, len(arr))
  945. for i, v := range arr {
  946. existingKeys[i] = string(v)
  947. }
  948. }
  949. } else {
  950. // 换行分隔格式
  951. existingKeys = strings.Split(strings.Trim(originChannel.Key, "\n"), "\n")
  952. }
  953. // 处理 Vertex AI 的特殊情况
  954. if channel.Type == constant.ChannelTypeVertexAi && channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey {
  955. // 尝试解析新密钥为JSON数组
  956. if strings.HasPrefix(strings.TrimSpace(channel.Key), "[") {
  957. array, err := getVertexArrayKeys(channel.Key)
  958. if err != nil {
  959. c.JSON(http.StatusOK, gin.H{
  960. "success": false,
  961. "message": "追加密钥解析失败: " + err.Error(),
  962. })
  963. return
  964. }
  965. newKeys = array
  966. } else {
  967. // 单个JSON密钥
  968. newKeys = []string{channel.Key}
  969. }
  970. } else {
  971. // 普通渠道的处理
  972. inputKeys := strings.Split(channel.Key, "\n")
  973. for _, key := range inputKeys {
  974. key = strings.TrimSpace(key)
  975. if key != "" {
  976. newKeys = append(newKeys, key)
  977. }
  978. }
  979. }
  980. seen := make(map[string]struct{}, len(existingKeys)+len(newKeys))
  981. for _, key := range existingKeys {
  982. normalized := strings.TrimSpace(key)
  983. if normalized == "" {
  984. continue
  985. }
  986. seen[normalized] = struct{}{}
  987. }
  988. dedupedNewKeys := make([]string, 0, len(newKeys))
  989. for _, key := range newKeys {
  990. normalized := strings.TrimSpace(key)
  991. if normalized == "" {
  992. continue
  993. }
  994. if _, ok := seen[normalized]; ok {
  995. continue
  996. }
  997. seen[normalized] = struct{}{}
  998. dedupedNewKeys = append(dedupedNewKeys, normalized)
  999. }
  1000. allKeys := append(existingKeys, dedupedNewKeys...)
  1001. channel.Key = strings.Join(allKeys, "\n")
  1002. }
  1003. case "replace":
  1004. // 覆盖模式:直接使用新密钥(默认行为,不需要特殊处理)
  1005. }
  1006. }
  1007. err = channel.Update()
  1008. if err != nil {
  1009. common.ApiError(c, err)
  1010. return
  1011. }
  1012. model.InitChannelCache()
  1013. service.ResetProxyClientCache()
  1014. channel.Key = ""
  1015. clearChannelInfo(&channel.Channel)
  1016. c.JSON(http.StatusOK, gin.H{
  1017. "success": true,
  1018. "message": "",
  1019. "data": channel,
  1020. })
  1021. return
  1022. }
  1023. func FetchModels(c *gin.Context) {
  1024. var req struct {
  1025. BaseURL string `json:"base_url"`
  1026. Type int `json:"type"`
  1027. Key string `json:"key"`
  1028. }
  1029. if err := c.ShouldBindJSON(&req); err != nil {
  1030. c.JSON(http.StatusBadRequest, gin.H{
  1031. "success": false,
  1032. "message": "Invalid request",
  1033. })
  1034. return
  1035. }
  1036. baseURL := req.BaseURL
  1037. if baseURL == "" {
  1038. baseURL = constant.ChannelBaseURLs[req.Type]
  1039. }
  1040. // remove line breaks and extra spaces.
  1041. key := strings.TrimSpace(req.Key)
  1042. key = strings.Split(key, "\n")[0]
  1043. if req.Type == constant.ChannelTypeOllama {
  1044. models, err := ollama.FetchOllamaModels(baseURL, key)
  1045. if err != nil {
  1046. c.JSON(http.StatusOK, gin.H{
  1047. "success": false,
  1048. "message": fmt.Sprintf("获取Ollama模型失败: %s", err.Error()),
  1049. })
  1050. return
  1051. }
  1052. names := make([]string, 0, len(models))
  1053. for _, modelInfo := range models {
  1054. names = append(names, modelInfo.Name)
  1055. }
  1056. c.JSON(http.StatusOK, gin.H{
  1057. "success": true,
  1058. "data": names,
  1059. })
  1060. return
  1061. }
  1062. if req.Type == constant.ChannelTypeGemini {
  1063. models, err := gemini.FetchGeminiModels(baseURL, key, "")
  1064. if err != nil {
  1065. c.JSON(http.StatusOK, gin.H{
  1066. "success": false,
  1067. "message": fmt.Sprintf("获取Gemini模型失败: %s", err.Error()),
  1068. })
  1069. return
  1070. }
  1071. c.JSON(http.StatusOK, gin.H{
  1072. "success": true,
  1073. "data": models,
  1074. })
  1075. return
  1076. }
  1077. client := &http.Client{}
  1078. url := fmt.Sprintf("%s/v1/models", baseURL)
  1079. request, err := http.NewRequest("GET", url, nil)
  1080. if err != nil {
  1081. c.JSON(http.StatusInternalServerError, gin.H{
  1082. "success": false,
  1083. "message": err.Error(),
  1084. })
  1085. return
  1086. }
  1087. request.Header.Set("Authorization", "Bearer "+key)
  1088. response, err := client.Do(request)
  1089. if err != nil {
  1090. c.JSON(http.StatusInternalServerError, gin.H{
  1091. "success": false,
  1092. "message": err.Error(),
  1093. })
  1094. return
  1095. }
  1096. //check status code
  1097. if response.StatusCode != http.StatusOK {
  1098. c.JSON(http.StatusInternalServerError, gin.H{
  1099. "success": false,
  1100. "message": "Failed to fetch models",
  1101. })
  1102. return
  1103. }
  1104. defer response.Body.Close()
  1105. var result struct {
  1106. Data []struct {
  1107. ID string `json:"id"`
  1108. } `json:"data"`
  1109. }
  1110. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  1111. c.JSON(http.StatusInternalServerError, gin.H{
  1112. "success": false,
  1113. "message": err.Error(),
  1114. })
  1115. return
  1116. }
  1117. var models []string
  1118. for _, model := range result.Data {
  1119. models = append(models, model.ID)
  1120. }
  1121. c.JSON(http.StatusOK, gin.H{
  1122. "success": true,
  1123. "data": models,
  1124. })
  1125. }
  1126. func BatchSetChannelTag(c *gin.Context) {
  1127. channelBatch := ChannelBatch{}
  1128. err := c.ShouldBindJSON(&channelBatch)
  1129. if err != nil || len(channelBatch.Ids) == 0 {
  1130. c.JSON(http.StatusOK, gin.H{
  1131. "success": false,
  1132. "message": "参数错误",
  1133. })
  1134. return
  1135. }
  1136. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  1137. if err != nil {
  1138. common.ApiError(c, err)
  1139. return
  1140. }
  1141. model.InitChannelCache()
  1142. c.JSON(http.StatusOK, gin.H{
  1143. "success": true,
  1144. "message": "",
  1145. "data": len(channelBatch.Ids),
  1146. })
  1147. return
  1148. }
  1149. func GetTagModels(c *gin.Context) {
  1150. tag := c.Query("tag")
  1151. if tag == "" {
  1152. c.JSON(http.StatusBadRequest, gin.H{
  1153. "success": false,
  1154. "message": "tag不能为空",
  1155. })
  1156. return
  1157. }
  1158. channels, err := model.GetChannelsByTag(tag, false, false) // idSort=false, selectAll=false
  1159. if err != nil {
  1160. c.JSON(http.StatusInternalServerError, gin.H{
  1161. "success": false,
  1162. "message": err.Error(),
  1163. })
  1164. return
  1165. }
  1166. var longestModels string
  1167. maxLength := 0
  1168. // Find the longest models string among all channels with the given tag
  1169. for _, channel := range channels {
  1170. if channel.Models != "" {
  1171. currentModels := strings.Split(channel.Models, ",")
  1172. if len(currentModels) > maxLength {
  1173. maxLength = len(currentModels)
  1174. longestModels = channel.Models
  1175. }
  1176. }
  1177. }
  1178. c.JSON(http.StatusOK, gin.H{
  1179. "success": true,
  1180. "message": "",
  1181. "data": longestModels,
  1182. })
  1183. return
  1184. }
  1185. // CopyChannel handles cloning an existing channel with its key.
  1186. // POST /api/channel/copy/:id
  1187. // Optional query params:
  1188. //
  1189. // suffix - string appended to the original name (default "_复制")
  1190. // reset_balance - bool, when true will reset balance & used_quota to 0 (default true)
  1191. func CopyChannel(c *gin.Context) {
  1192. id, err := strconv.Atoi(c.Param("id"))
  1193. if err != nil {
  1194. c.JSON(http.StatusOK, gin.H{"success": false, "message": "invalid id"})
  1195. return
  1196. }
  1197. suffix := c.DefaultQuery("suffix", "_复制")
  1198. resetBalance := true
  1199. if rbStr := c.DefaultQuery("reset_balance", "true"); rbStr != "" {
  1200. if v, err := strconv.ParseBool(rbStr); err == nil {
  1201. resetBalance = v
  1202. }
  1203. }
  1204. // fetch original channel with key
  1205. origin, err := model.GetChannelById(id, true)
  1206. if err != nil {
  1207. common.SysError("failed to get channel by id: " + err.Error())
  1208. c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取渠道信息失败,请稍后重试"})
  1209. return
  1210. }
  1211. // clone channel
  1212. clone := *origin // shallow copy is sufficient as we will overwrite primitives
  1213. clone.Id = 0 // let DB auto-generate
  1214. clone.CreatedTime = common.GetTimestamp()
  1215. clone.Name = origin.Name + suffix
  1216. clone.TestTime = 0
  1217. clone.ResponseTime = 0
  1218. if resetBalance {
  1219. clone.Balance = 0
  1220. clone.UsedQuota = 0
  1221. }
  1222. // insert
  1223. if err := model.BatchInsertChannels([]model.Channel{clone}); err != nil {
  1224. common.SysError("failed to clone channel: " + err.Error())
  1225. c.JSON(http.StatusOK, gin.H{"success": false, "message": "复制渠道失败,请稍后重试"})
  1226. return
  1227. }
  1228. model.InitChannelCache()
  1229. // success
  1230. c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": gin.H{"id": clone.Id}})
  1231. }
  1232. // MultiKeyManageRequest represents the request for multi-key management operations
  1233. type MultiKeyManageRequest struct {
  1234. ChannelId int `json:"channel_id"`
  1235. Action string `json:"action"` // "disable_key", "enable_key", "delete_key", "delete_disabled_keys", "get_key_status"
  1236. KeyIndex *int `json:"key_index,omitempty"` // for disable_key, enable_key, and delete_key actions
  1237. Page int `json:"page,omitempty"` // for get_key_status pagination
  1238. PageSize int `json:"page_size,omitempty"` // for get_key_status pagination
  1239. Status *int `json:"status,omitempty"` // for get_key_status filtering: 1=enabled, 2=manual_disabled, 3=auto_disabled, nil=all
  1240. }
  1241. // MultiKeyStatusResponse represents the response for key status query
  1242. type MultiKeyStatusResponse struct {
  1243. Keys []KeyStatus `json:"keys"`
  1244. Total int `json:"total"`
  1245. Page int `json:"page"`
  1246. PageSize int `json:"page_size"`
  1247. TotalPages int `json:"total_pages"`
  1248. // Statistics
  1249. EnabledCount int `json:"enabled_count"`
  1250. ManualDisabledCount int `json:"manual_disabled_count"`
  1251. AutoDisabledCount int `json:"auto_disabled_count"`
  1252. }
  1253. type KeyStatus struct {
  1254. Index int `json:"index"`
  1255. Status int `json:"status"` // 1: enabled, 2: disabled
  1256. DisabledTime int64 `json:"disabled_time,omitempty"`
  1257. Reason string `json:"reason,omitempty"`
  1258. KeyPreview string `json:"key_preview"` // first 10 chars of key for identification
  1259. }
  1260. // ManageMultiKeys handles multi-key management operations
  1261. func ManageMultiKeys(c *gin.Context) {
  1262. request := MultiKeyManageRequest{}
  1263. err := c.ShouldBindJSON(&request)
  1264. if err != nil {
  1265. common.ApiError(c, err)
  1266. return
  1267. }
  1268. channel, err := model.GetChannelById(request.ChannelId, true)
  1269. if err != nil {
  1270. c.JSON(http.StatusOK, gin.H{
  1271. "success": false,
  1272. "message": "渠道不存在",
  1273. })
  1274. return
  1275. }
  1276. if !channel.ChannelInfo.IsMultiKey {
  1277. c.JSON(http.StatusOK, gin.H{
  1278. "success": false,
  1279. "message": "该渠道不是多密钥模式",
  1280. })
  1281. return
  1282. }
  1283. lock := model.GetChannelPollingLock(channel.Id)
  1284. lock.Lock()
  1285. defer lock.Unlock()
  1286. switch request.Action {
  1287. case "get_key_status":
  1288. keys := channel.GetKeys()
  1289. // Default pagination parameters
  1290. page := request.Page
  1291. pageSize := request.PageSize
  1292. if page <= 0 {
  1293. page = 1
  1294. }
  1295. if pageSize <= 0 {
  1296. pageSize = 50 // Default page size
  1297. }
  1298. // Statistics for all keys (unchanged by filtering)
  1299. var enabledCount, manualDisabledCount, autoDisabledCount int
  1300. // Build all key status data first
  1301. var allKeyStatusList []KeyStatus
  1302. for i, key := range keys {
  1303. status := 1 // default enabled
  1304. var disabledTime int64
  1305. var reason string
  1306. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1307. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1308. status = s
  1309. }
  1310. }
  1311. // Count for statistics (all keys)
  1312. switch status {
  1313. case 1:
  1314. enabledCount++
  1315. case 2:
  1316. manualDisabledCount++
  1317. case 3:
  1318. autoDisabledCount++
  1319. }
  1320. if status != 1 {
  1321. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1322. disabledTime = channel.ChannelInfo.MultiKeyDisabledTime[i]
  1323. }
  1324. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1325. reason = channel.ChannelInfo.MultiKeyDisabledReason[i]
  1326. }
  1327. }
  1328. // Create key preview (first 10 chars)
  1329. keyPreview := key
  1330. if len(key) > 10 {
  1331. keyPreview = key[:10] + "..."
  1332. }
  1333. allKeyStatusList = append(allKeyStatusList, KeyStatus{
  1334. Index: i,
  1335. Status: status,
  1336. DisabledTime: disabledTime,
  1337. Reason: reason,
  1338. KeyPreview: keyPreview,
  1339. })
  1340. }
  1341. // Apply status filter if specified
  1342. var filteredKeyStatusList []KeyStatus
  1343. if request.Status != nil {
  1344. for _, keyStatus := range allKeyStatusList {
  1345. if keyStatus.Status == *request.Status {
  1346. filteredKeyStatusList = append(filteredKeyStatusList, keyStatus)
  1347. }
  1348. }
  1349. } else {
  1350. filteredKeyStatusList = allKeyStatusList
  1351. }
  1352. // Calculate pagination based on filtered results
  1353. filteredTotal := len(filteredKeyStatusList)
  1354. totalPages := (filteredTotal + pageSize - 1) / pageSize
  1355. if totalPages == 0 {
  1356. totalPages = 1
  1357. }
  1358. if page > totalPages {
  1359. page = totalPages
  1360. }
  1361. // Calculate range for current page
  1362. start := (page - 1) * pageSize
  1363. end := start + pageSize
  1364. if end > filteredTotal {
  1365. end = filteredTotal
  1366. }
  1367. // Get the page data
  1368. var pageKeyStatusList []KeyStatus
  1369. if start < filteredTotal {
  1370. pageKeyStatusList = filteredKeyStatusList[start:end]
  1371. }
  1372. c.JSON(http.StatusOK, gin.H{
  1373. "success": true,
  1374. "message": "",
  1375. "data": MultiKeyStatusResponse{
  1376. Keys: pageKeyStatusList,
  1377. Total: filteredTotal, // Total of filtered results
  1378. Page: page,
  1379. PageSize: pageSize,
  1380. TotalPages: totalPages,
  1381. EnabledCount: enabledCount, // Overall statistics
  1382. ManualDisabledCount: manualDisabledCount, // Overall statistics
  1383. AutoDisabledCount: autoDisabledCount, // Overall statistics
  1384. },
  1385. })
  1386. return
  1387. case "disable_key":
  1388. if request.KeyIndex == nil {
  1389. c.JSON(http.StatusOK, gin.H{
  1390. "success": false,
  1391. "message": "未指定要禁用的密钥索引",
  1392. })
  1393. return
  1394. }
  1395. keyIndex := *request.KeyIndex
  1396. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1397. c.JSON(http.StatusOK, gin.H{
  1398. "success": false,
  1399. "message": "密钥索引超出范围",
  1400. })
  1401. return
  1402. }
  1403. if channel.ChannelInfo.MultiKeyStatusList == nil {
  1404. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1405. }
  1406. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  1407. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1408. }
  1409. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  1410. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1411. }
  1412. channel.ChannelInfo.MultiKeyStatusList[keyIndex] = 2 // disabled
  1413. err = channel.Update()
  1414. if err != nil {
  1415. common.ApiError(c, err)
  1416. return
  1417. }
  1418. model.InitChannelCache()
  1419. c.JSON(http.StatusOK, gin.H{
  1420. "success": true,
  1421. "message": "密钥已禁用",
  1422. })
  1423. return
  1424. case "enable_key":
  1425. if request.KeyIndex == nil {
  1426. c.JSON(http.StatusOK, gin.H{
  1427. "success": false,
  1428. "message": "未指定要启用的密钥索引",
  1429. })
  1430. return
  1431. }
  1432. keyIndex := *request.KeyIndex
  1433. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1434. c.JSON(http.StatusOK, gin.H{
  1435. "success": false,
  1436. "message": "密钥索引超出范围",
  1437. })
  1438. return
  1439. }
  1440. // 从状态列表中删除该密钥的记录,使其回到默认启用状态
  1441. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1442. delete(channel.ChannelInfo.MultiKeyStatusList, keyIndex)
  1443. }
  1444. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1445. delete(channel.ChannelInfo.MultiKeyDisabledTime, keyIndex)
  1446. }
  1447. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1448. delete(channel.ChannelInfo.MultiKeyDisabledReason, keyIndex)
  1449. }
  1450. err = channel.Update()
  1451. if err != nil {
  1452. common.ApiError(c, err)
  1453. return
  1454. }
  1455. model.InitChannelCache()
  1456. c.JSON(http.StatusOK, gin.H{
  1457. "success": true,
  1458. "message": "密钥已启用",
  1459. })
  1460. return
  1461. case "enable_all_keys":
  1462. // 清空所有禁用状态,使所有密钥回到默认启用状态
  1463. var enabledCount int
  1464. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1465. enabledCount = len(channel.ChannelInfo.MultiKeyStatusList)
  1466. }
  1467. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1468. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1469. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1470. err = channel.Update()
  1471. if err != nil {
  1472. common.ApiError(c, err)
  1473. return
  1474. }
  1475. model.InitChannelCache()
  1476. c.JSON(http.StatusOK, gin.H{
  1477. "success": true,
  1478. "message": fmt.Sprintf("已启用 %d 个密钥", enabledCount),
  1479. })
  1480. return
  1481. case "disable_all_keys":
  1482. // 禁用所有启用的密钥
  1483. if channel.ChannelInfo.MultiKeyStatusList == nil {
  1484. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1485. }
  1486. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  1487. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1488. }
  1489. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  1490. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1491. }
  1492. var disabledCount int
  1493. for i := 0; i < channel.ChannelInfo.MultiKeySize; i++ {
  1494. status := 1 // default enabled
  1495. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1496. status = s
  1497. }
  1498. // 只禁用当前启用的密钥
  1499. if status == 1 {
  1500. channel.ChannelInfo.MultiKeyStatusList[i] = 2 // disabled
  1501. disabledCount++
  1502. }
  1503. }
  1504. if disabledCount == 0 {
  1505. c.JSON(http.StatusOK, gin.H{
  1506. "success": false,
  1507. "message": "没有可禁用的密钥",
  1508. })
  1509. return
  1510. }
  1511. err = channel.Update()
  1512. if err != nil {
  1513. common.ApiError(c, err)
  1514. return
  1515. }
  1516. model.InitChannelCache()
  1517. c.JSON(http.StatusOK, gin.H{
  1518. "success": true,
  1519. "message": fmt.Sprintf("已禁用 %d 个密钥", disabledCount),
  1520. })
  1521. return
  1522. case "delete_key":
  1523. if request.KeyIndex == nil {
  1524. c.JSON(http.StatusOK, gin.H{
  1525. "success": false,
  1526. "message": "未指定要删除的密钥索引",
  1527. })
  1528. return
  1529. }
  1530. keyIndex := *request.KeyIndex
  1531. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1532. c.JSON(http.StatusOK, gin.H{
  1533. "success": false,
  1534. "message": "密钥索引超出范围",
  1535. })
  1536. return
  1537. }
  1538. keys := channel.GetKeys()
  1539. var remainingKeys []string
  1540. var newStatusList = make(map[int]int)
  1541. var newDisabledTime = make(map[int]int64)
  1542. var newDisabledReason = make(map[int]string)
  1543. newIndex := 0
  1544. for i, key := range keys {
  1545. // 跳过要删除的密钥
  1546. if i == keyIndex {
  1547. continue
  1548. }
  1549. remainingKeys = append(remainingKeys, key)
  1550. // 保留其他密钥的状态信息,重新索引
  1551. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1552. if status, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists && status != 1 {
  1553. newStatusList[newIndex] = status
  1554. }
  1555. }
  1556. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1557. if t, exists := channel.ChannelInfo.MultiKeyDisabledTime[i]; exists {
  1558. newDisabledTime[newIndex] = t
  1559. }
  1560. }
  1561. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1562. if r, exists := channel.ChannelInfo.MultiKeyDisabledReason[i]; exists {
  1563. newDisabledReason[newIndex] = r
  1564. }
  1565. }
  1566. newIndex++
  1567. }
  1568. if len(remainingKeys) == 0 {
  1569. c.JSON(http.StatusOK, gin.H{
  1570. "success": false,
  1571. "message": "不能删除最后一个密钥",
  1572. })
  1573. return
  1574. }
  1575. // Update channel with remaining keys
  1576. channel.Key = strings.Join(remainingKeys, "\n")
  1577. channel.ChannelInfo.MultiKeySize = len(remainingKeys)
  1578. channel.ChannelInfo.MultiKeyStatusList = newStatusList
  1579. channel.ChannelInfo.MultiKeyDisabledTime = newDisabledTime
  1580. channel.ChannelInfo.MultiKeyDisabledReason = newDisabledReason
  1581. err = channel.Update()
  1582. if err != nil {
  1583. common.ApiError(c, err)
  1584. return
  1585. }
  1586. model.InitChannelCache()
  1587. c.JSON(http.StatusOK, gin.H{
  1588. "success": true,
  1589. "message": "密钥已删除",
  1590. })
  1591. return
  1592. case "delete_disabled_keys":
  1593. keys := channel.GetKeys()
  1594. var remainingKeys []string
  1595. var deletedCount int
  1596. var newStatusList = make(map[int]int)
  1597. var newDisabledTime = make(map[int]int64)
  1598. var newDisabledReason = make(map[int]string)
  1599. newIndex := 0
  1600. for i, key := range keys {
  1601. status := 1 // default enabled
  1602. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1603. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1604. status = s
  1605. }
  1606. }
  1607. // 只删除自动禁用(status == 3)的密钥,保留启用(status == 1)和手动禁用(status == 2)的密钥
  1608. if status == 3 {
  1609. deletedCount++
  1610. } else {
  1611. remainingKeys = append(remainingKeys, key)
  1612. // 保留非自动禁用密钥的状态信息,重新索引
  1613. if status != 1 {
  1614. newStatusList[newIndex] = status
  1615. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1616. if t, exists := channel.ChannelInfo.MultiKeyDisabledTime[i]; exists {
  1617. newDisabledTime[newIndex] = t
  1618. }
  1619. }
  1620. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1621. if r, exists := channel.ChannelInfo.MultiKeyDisabledReason[i]; exists {
  1622. newDisabledReason[newIndex] = r
  1623. }
  1624. }
  1625. }
  1626. newIndex++
  1627. }
  1628. }
  1629. if deletedCount == 0 {
  1630. c.JSON(http.StatusOK, gin.H{
  1631. "success": false,
  1632. "message": "没有需要删除的自动禁用密钥",
  1633. })
  1634. return
  1635. }
  1636. // Update channel with remaining keys
  1637. channel.Key = strings.Join(remainingKeys, "\n")
  1638. channel.ChannelInfo.MultiKeySize = len(remainingKeys)
  1639. channel.ChannelInfo.MultiKeyStatusList = newStatusList
  1640. channel.ChannelInfo.MultiKeyDisabledTime = newDisabledTime
  1641. channel.ChannelInfo.MultiKeyDisabledReason = newDisabledReason
  1642. err = channel.Update()
  1643. if err != nil {
  1644. common.ApiError(c, err)
  1645. return
  1646. }
  1647. model.InitChannelCache()
  1648. c.JSON(http.StatusOK, gin.H{
  1649. "success": true,
  1650. "message": fmt.Sprintf("已删除 %d 个自动禁用的密钥", deletedCount),
  1651. "data": deletedCount,
  1652. })
  1653. return
  1654. default:
  1655. c.JSON(http.StatusOK, gin.H{
  1656. "success": false,
  1657. "message": "不支持的操作",
  1658. })
  1659. return
  1660. }
  1661. }
  1662. // OllamaPullModel 拉取 Ollama 模型
  1663. func OllamaPullModel(c *gin.Context) {
  1664. var req struct {
  1665. ChannelID int `json:"channel_id"`
  1666. ModelName string `json:"model_name"`
  1667. }
  1668. if err := c.ShouldBindJSON(&req); err != nil {
  1669. c.JSON(http.StatusBadRequest, gin.H{
  1670. "success": false,
  1671. "message": "Invalid request parameters",
  1672. })
  1673. return
  1674. }
  1675. if req.ChannelID == 0 || req.ModelName == "" {
  1676. c.JSON(http.StatusBadRequest, gin.H{
  1677. "success": false,
  1678. "message": "Channel ID and model name are required",
  1679. })
  1680. return
  1681. }
  1682. // 获取渠道信息
  1683. channel, err := model.GetChannelById(req.ChannelID, true)
  1684. if err != nil {
  1685. c.JSON(http.StatusNotFound, gin.H{
  1686. "success": false,
  1687. "message": "Channel not found",
  1688. })
  1689. return
  1690. }
  1691. // 检查是否是 Ollama 渠道
  1692. if channel.Type != constant.ChannelTypeOllama {
  1693. c.JSON(http.StatusBadRequest, gin.H{
  1694. "success": false,
  1695. "message": "This operation is only supported for Ollama channels",
  1696. })
  1697. return
  1698. }
  1699. baseURL := constant.ChannelBaseURLs[channel.Type]
  1700. if channel.GetBaseURL() != "" {
  1701. baseURL = channel.GetBaseURL()
  1702. }
  1703. key := strings.Split(channel.Key, "\n")[0]
  1704. err = ollama.PullOllamaModel(baseURL, key, req.ModelName)
  1705. if err != nil {
  1706. c.JSON(http.StatusInternalServerError, gin.H{
  1707. "success": false,
  1708. "message": fmt.Sprintf("Failed to pull model: %s", err.Error()),
  1709. })
  1710. return
  1711. }
  1712. c.JSON(http.StatusOK, gin.H{
  1713. "success": true,
  1714. "message": fmt.Sprintf("Model %s pulled successfully", req.ModelName),
  1715. })
  1716. }
  1717. // OllamaPullModelStream 流式拉取 Ollama 模型
  1718. func OllamaPullModelStream(c *gin.Context) {
  1719. var req struct {
  1720. ChannelID int `json:"channel_id"`
  1721. ModelName string `json:"model_name"`
  1722. }
  1723. if err := c.ShouldBindJSON(&req); err != nil {
  1724. c.JSON(http.StatusBadRequest, gin.H{
  1725. "success": false,
  1726. "message": "Invalid request parameters",
  1727. })
  1728. return
  1729. }
  1730. if req.ChannelID == 0 || req.ModelName == "" {
  1731. c.JSON(http.StatusBadRequest, gin.H{
  1732. "success": false,
  1733. "message": "Channel ID and model name are required",
  1734. })
  1735. return
  1736. }
  1737. // 获取渠道信息
  1738. channel, err := model.GetChannelById(req.ChannelID, true)
  1739. if err != nil {
  1740. c.JSON(http.StatusNotFound, gin.H{
  1741. "success": false,
  1742. "message": "Channel not found",
  1743. })
  1744. return
  1745. }
  1746. // 检查是否是 Ollama 渠道
  1747. if channel.Type != constant.ChannelTypeOllama {
  1748. c.JSON(http.StatusBadRequest, gin.H{
  1749. "success": false,
  1750. "message": "This operation is only supported for Ollama channels",
  1751. })
  1752. return
  1753. }
  1754. baseURL := constant.ChannelBaseURLs[channel.Type]
  1755. if channel.GetBaseURL() != "" {
  1756. baseURL = channel.GetBaseURL()
  1757. }
  1758. // 设置 SSE 头部
  1759. c.Header("Content-Type", "text/event-stream")
  1760. c.Header("Cache-Control", "no-cache")
  1761. c.Header("Connection", "keep-alive")
  1762. c.Header("Access-Control-Allow-Origin", "*")
  1763. key := strings.Split(channel.Key, "\n")[0]
  1764. // 创建进度回调函数
  1765. progressCallback := func(progress ollama.OllamaPullResponse) {
  1766. data, _ := json.Marshal(progress)
  1767. fmt.Fprintf(c.Writer, "data: %s\n\n", string(data))
  1768. c.Writer.Flush()
  1769. }
  1770. // 执行拉取
  1771. err = ollama.PullOllamaModelStream(baseURL, key, req.ModelName, progressCallback)
  1772. if err != nil {
  1773. errorData, _ := json.Marshal(gin.H{
  1774. "error": err.Error(),
  1775. })
  1776. fmt.Fprintf(c.Writer, "data: %s\n\n", string(errorData))
  1777. } else {
  1778. successData, _ := json.Marshal(gin.H{
  1779. "message": fmt.Sprintf("Model %s pulled successfully", req.ModelName),
  1780. })
  1781. fmt.Fprintf(c.Writer, "data: %s\n\n", string(successData))
  1782. }
  1783. // 发送结束标志
  1784. fmt.Fprintf(c.Writer, "data: [DONE]\n\n")
  1785. c.Writer.Flush()
  1786. }
  1787. // OllamaDeleteModel 删除 Ollama 模型
  1788. func OllamaDeleteModel(c *gin.Context) {
  1789. var req struct {
  1790. ChannelID int `json:"channel_id"`
  1791. ModelName string `json:"model_name"`
  1792. }
  1793. if err := c.ShouldBindJSON(&req); err != nil {
  1794. c.JSON(http.StatusBadRequest, gin.H{
  1795. "success": false,
  1796. "message": "Invalid request parameters",
  1797. })
  1798. return
  1799. }
  1800. if req.ChannelID == 0 || req.ModelName == "" {
  1801. c.JSON(http.StatusBadRequest, gin.H{
  1802. "success": false,
  1803. "message": "Channel ID and model name are required",
  1804. })
  1805. return
  1806. }
  1807. // 获取渠道信息
  1808. channel, err := model.GetChannelById(req.ChannelID, true)
  1809. if err != nil {
  1810. c.JSON(http.StatusNotFound, gin.H{
  1811. "success": false,
  1812. "message": "Channel not found",
  1813. })
  1814. return
  1815. }
  1816. // 检查是否是 Ollama 渠道
  1817. if channel.Type != constant.ChannelTypeOllama {
  1818. c.JSON(http.StatusBadRequest, gin.H{
  1819. "success": false,
  1820. "message": "This operation is only supported for Ollama channels",
  1821. })
  1822. return
  1823. }
  1824. baseURL := constant.ChannelBaseURLs[channel.Type]
  1825. if channel.GetBaseURL() != "" {
  1826. baseURL = channel.GetBaseURL()
  1827. }
  1828. key := strings.Split(channel.Key, "\n")[0]
  1829. err = ollama.DeleteOllamaModel(baseURL, key, req.ModelName)
  1830. if err != nil {
  1831. c.JSON(http.StatusInternalServerError, gin.H{
  1832. "success": false,
  1833. "message": fmt.Sprintf("Failed to delete model: %s", err.Error()),
  1834. })
  1835. return
  1836. }
  1837. c.JSON(http.StatusOK, gin.H{
  1838. "success": true,
  1839. "message": fmt.Sprintf("Model %s deleted successfully", req.ModelName),
  1840. })
  1841. }
  1842. // OllamaVersion 获取 Ollama 服务版本信息
  1843. func OllamaVersion(c *gin.Context) {
  1844. id, err := strconv.Atoi(c.Param("id"))
  1845. if err != nil {
  1846. c.JSON(http.StatusBadRequest, gin.H{
  1847. "success": false,
  1848. "message": "Invalid channel id",
  1849. })
  1850. return
  1851. }
  1852. channel, err := model.GetChannelById(id, true)
  1853. if err != nil {
  1854. c.JSON(http.StatusNotFound, gin.H{
  1855. "success": false,
  1856. "message": "Channel not found",
  1857. })
  1858. return
  1859. }
  1860. if channel.Type != constant.ChannelTypeOllama {
  1861. c.JSON(http.StatusBadRequest, gin.H{
  1862. "success": false,
  1863. "message": "This operation is only supported for Ollama channels",
  1864. })
  1865. return
  1866. }
  1867. baseURL := constant.ChannelBaseURLs[channel.Type]
  1868. if channel.GetBaseURL() != "" {
  1869. baseURL = channel.GetBaseURL()
  1870. }
  1871. key := strings.Split(channel.Key, "\n")[0]
  1872. version, err := ollama.FetchOllamaVersion(baseURL, key)
  1873. if err != nil {
  1874. c.JSON(http.StatusOK, gin.H{
  1875. "success": false,
  1876. "message": fmt.Sprintf("获取Ollama版本失败: %s", err.Error()),
  1877. })
  1878. return
  1879. }
  1880. c.JSON(http.StatusOK, gin.H{
  1881. "success": true,
  1882. "data": gin.H{
  1883. "version": version,
  1884. },
  1885. })
  1886. }
  1887. // GetUserChannelsForBinding 获取用户可用于绑定的渠道列表
  1888. // 只返回 id、name、type 和 remark,不包含敏感信息(如key)
  1889. func GetUserChannelsForBinding(c *gin.Context) {
  1890. channels, err := model.GetAllChannelsForBinding()
  1891. if err != nil {
  1892. common.ApiError(c, err)
  1893. return
  1894. }
  1895. // 构建返回结果
  1896. result := make([]gin.H, 0, len(channels))
  1897. for _, ch := range channels {
  1898. result = append(result, gin.H{
  1899. "id": ch.Id,
  1900. "name": ch.Name,
  1901. "public_name": ch.PublicName,
  1902. "type": ch.Type,
  1903. "remark": ch.Remark,
  1904. })
  1905. }
  1906. c.JSON(http.StatusOK, gin.H{
  1907. "success": true,
  1908. "message": "",
  1909. "data": result,
  1910. })
  1911. }