channel.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/constant"
  8. "one-api/model"
  9. "strconv"
  10. "strings"
  11. "github.com/gin-gonic/gin"
  12. )
  13. type OpenAIModel struct {
  14. ID string `json:"id"`
  15. Object string `json:"object"`
  16. Created int64 `json:"created"`
  17. OwnedBy string `json:"owned_by"`
  18. Permission []struct {
  19. ID string `json:"id"`
  20. Object string `json:"object"`
  21. Created int64 `json:"created"`
  22. AllowCreateEngine bool `json:"allow_create_engine"`
  23. AllowSampling bool `json:"allow_sampling"`
  24. AllowLogprobs bool `json:"allow_logprobs"`
  25. AllowSearchIndices bool `json:"allow_search_indices"`
  26. AllowView bool `json:"allow_view"`
  27. AllowFineTuning bool `json:"allow_fine_tuning"`
  28. Organization string `json:"organization"`
  29. Group string `json:"group"`
  30. IsBlocking bool `json:"is_blocking"`
  31. } `json:"permission"`
  32. Root string `json:"root"`
  33. Parent string `json:"parent"`
  34. }
  35. type OpenAIModelsResponse struct {
  36. Data []OpenAIModel `json:"data"`
  37. Success bool `json:"success"`
  38. }
  39. func parseStatusFilter(statusParam string) int {
  40. switch strings.ToLower(statusParam) {
  41. case "enabled", "1":
  42. return common.ChannelStatusEnabled
  43. case "disabled", "0":
  44. return 0
  45. default:
  46. return -1
  47. }
  48. }
  49. func GetAllChannels(c *gin.Context) {
  50. pageInfo := common.GetPageQuery(c)
  51. channelData := make([]*model.Channel, 0)
  52. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  53. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  54. statusParam := c.Query("status")
  55. // statusFilter: -1 all, 1 enabled, 0 disabled (include auto & manual)
  56. statusFilter := parseStatusFilter(statusParam)
  57. // type filter
  58. typeStr := c.Query("type")
  59. typeFilter := -1
  60. if typeStr != "" {
  61. if t, err := strconv.Atoi(typeStr); err == nil {
  62. typeFilter = t
  63. }
  64. }
  65. var total int64
  66. if enableTagMode {
  67. tags, err := model.GetPaginatedTags(pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  68. if err != nil {
  69. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  70. return
  71. }
  72. for _, tag := range tags {
  73. if tag == nil || *tag == "" {
  74. continue
  75. }
  76. tagChannels, err := model.GetChannelsByTag(*tag, idSort)
  77. if err != nil {
  78. continue
  79. }
  80. filtered := make([]*model.Channel, 0)
  81. for _, ch := range tagChannels {
  82. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  83. continue
  84. }
  85. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  86. continue
  87. }
  88. if typeFilter >= 0 && ch.Type != typeFilter {
  89. continue
  90. }
  91. filtered = append(filtered, ch)
  92. }
  93. channelData = append(channelData, filtered...)
  94. }
  95. total, _ = model.CountAllTags()
  96. } else {
  97. baseQuery := model.DB.Model(&model.Channel{})
  98. if typeFilter >= 0 {
  99. baseQuery = baseQuery.Where("type = ?", typeFilter)
  100. }
  101. if statusFilter == common.ChannelStatusEnabled {
  102. baseQuery = baseQuery.Where("status = ?", common.ChannelStatusEnabled)
  103. } else if statusFilter == 0 {
  104. baseQuery = baseQuery.Where("status != ?", common.ChannelStatusEnabled)
  105. }
  106. baseQuery.Count(&total)
  107. order := "priority desc"
  108. if idSort {
  109. order = "id desc"
  110. }
  111. err := baseQuery.Order(order).Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("key").Find(&channelData).Error
  112. if err != nil {
  113. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  114. return
  115. }
  116. }
  117. countQuery := model.DB.Model(&model.Channel{})
  118. if statusFilter == common.ChannelStatusEnabled {
  119. countQuery = countQuery.Where("status = ?", common.ChannelStatusEnabled)
  120. } else if statusFilter == 0 {
  121. countQuery = countQuery.Where("status != ?", common.ChannelStatusEnabled)
  122. }
  123. var results []struct {
  124. Type int64
  125. Count int64
  126. }
  127. _ = countQuery.Select("type, count(*) as count").Group("type").Find(&results).Error
  128. typeCounts := make(map[int64]int64)
  129. for _, r := range results {
  130. typeCounts[r.Type] = r.Count
  131. }
  132. common.ApiSuccess(c, gin.H{
  133. "items": channelData,
  134. "total": total,
  135. "page": pageInfo.GetPage(),
  136. "page_size": pageInfo.GetPageSize(),
  137. "type_counts": typeCounts,
  138. })
  139. return
  140. }
  141. func FetchUpstreamModels(c *gin.Context) {
  142. id, err := strconv.Atoi(c.Param("id"))
  143. if err != nil {
  144. common.ApiError(c, err)
  145. return
  146. }
  147. channel, err := model.GetChannelById(id, true)
  148. if err != nil {
  149. common.ApiError(c, err)
  150. return
  151. }
  152. baseURL := constant.ChannelBaseURLs[channel.Type]
  153. if channel.GetBaseURL() != "" {
  154. baseURL = channel.GetBaseURL()
  155. }
  156. url := fmt.Sprintf("%s/v1/models", baseURL)
  157. switch channel.Type {
  158. case constant.ChannelTypeGemini:
  159. url = fmt.Sprintf("%s/v1beta/openai/models", baseURL)
  160. case constant.ChannelTypeAli:
  161. url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
  162. }
  163. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  164. if err != nil {
  165. common.ApiError(c, err)
  166. return
  167. }
  168. var result OpenAIModelsResponse
  169. if err = json.Unmarshal(body, &result); err != nil {
  170. c.JSON(http.StatusOK, gin.H{
  171. "success": false,
  172. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  173. })
  174. return
  175. }
  176. var ids []string
  177. for _, model := range result.Data {
  178. id := model.ID
  179. if channel.Type == constant.ChannelTypeGemini {
  180. id = strings.TrimPrefix(id, "models/")
  181. }
  182. ids = append(ids, id)
  183. }
  184. c.JSON(http.StatusOK, gin.H{
  185. "success": true,
  186. "message": "",
  187. "data": ids,
  188. })
  189. }
  190. func FixChannelsAbilities(c *gin.Context) {
  191. success, fails, err := model.FixAbility()
  192. if err != nil {
  193. common.ApiError(c, err)
  194. return
  195. }
  196. c.JSON(http.StatusOK, gin.H{
  197. "success": true,
  198. "message": "",
  199. "data": gin.H{
  200. "success": success,
  201. "fails": fails,
  202. },
  203. })
  204. }
  205. func SearchChannels(c *gin.Context) {
  206. keyword := c.Query("keyword")
  207. group := c.Query("group")
  208. modelKeyword := c.Query("model")
  209. statusParam := c.Query("status")
  210. statusFilter := parseStatusFilter(statusParam)
  211. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  212. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  213. channelData := make([]*model.Channel, 0)
  214. if enableTagMode {
  215. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  216. if err != nil {
  217. c.JSON(http.StatusOK, gin.H{
  218. "success": false,
  219. "message": err.Error(),
  220. })
  221. return
  222. }
  223. for _, tag := range tags {
  224. if tag != nil && *tag != "" {
  225. tagChannel, err := model.GetChannelsByTag(*tag, idSort)
  226. if err == nil {
  227. channelData = append(channelData, tagChannel...)
  228. }
  229. }
  230. }
  231. } else {
  232. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  233. if err != nil {
  234. c.JSON(http.StatusOK, gin.H{
  235. "success": false,
  236. "message": err.Error(),
  237. })
  238. return
  239. }
  240. channelData = channels
  241. }
  242. if statusFilter == common.ChannelStatusEnabled || statusFilter == 0 {
  243. filtered := make([]*model.Channel, 0, len(channelData))
  244. for _, ch := range channelData {
  245. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  246. continue
  247. }
  248. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  249. continue
  250. }
  251. filtered = append(filtered, ch)
  252. }
  253. channelData = filtered
  254. }
  255. // calculate type counts for search results
  256. typeCounts := make(map[int64]int64)
  257. for _, channel := range channelData {
  258. typeCounts[int64(channel.Type)]++
  259. }
  260. typeParam := c.Query("type")
  261. typeFilter := -1
  262. if typeParam != "" {
  263. if tp, err := strconv.Atoi(typeParam); err == nil {
  264. typeFilter = tp
  265. }
  266. }
  267. if typeFilter >= 0 {
  268. filtered := make([]*model.Channel, 0, len(channelData))
  269. for _, ch := range channelData {
  270. if ch.Type == typeFilter {
  271. filtered = append(filtered, ch)
  272. }
  273. }
  274. channelData = filtered
  275. }
  276. page, _ := strconv.Atoi(c.DefaultQuery("p", "1"))
  277. pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
  278. if page < 1 {
  279. page = 1
  280. }
  281. if pageSize <= 0 {
  282. pageSize = 20
  283. }
  284. total := len(channelData)
  285. startIdx := (page - 1) * pageSize
  286. if startIdx > total {
  287. startIdx = total
  288. }
  289. endIdx := startIdx + pageSize
  290. if endIdx > total {
  291. endIdx = total
  292. }
  293. pagedData := channelData[startIdx:endIdx]
  294. c.JSON(http.StatusOK, gin.H{
  295. "success": true,
  296. "message": "",
  297. "data": gin.H{
  298. "items": pagedData,
  299. "total": total,
  300. "type_counts": typeCounts,
  301. },
  302. })
  303. return
  304. }
  305. func GetChannel(c *gin.Context) {
  306. id, err := strconv.Atoi(c.Param("id"))
  307. if err != nil {
  308. common.ApiError(c, err)
  309. return
  310. }
  311. channel, err := model.GetChannelById(id, false)
  312. if err != nil {
  313. common.ApiError(c, err)
  314. return
  315. }
  316. c.JSON(http.StatusOK, gin.H{
  317. "success": true,
  318. "message": "",
  319. "data": channel,
  320. })
  321. return
  322. }
  323. // validateChannel 通用的渠道校验函数
  324. func validateChannel(channel *model.Channel, isAdd bool) error {
  325. // 校验 channel settings
  326. if err := channel.ValidateSettings(); err != nil {
  327. return fmt.Errorf("渠道额外设置[channel setting] 格式错误:%s", err.Error())
  328. }
  329. // 如果是添加操作,检查 channel 和 key 是否为空
  330. if isAdd {
  331. if channel == nil || channel.Key == "" {
  332. return fmt.Errorf("channel cannot be empty")
  333. }
  334. // 检查模型名称长度是否超过 255
  335. for _, m := range channel.GetModels() {
  336. if len(m) > 255 {
  337. return fmt.Errorf("模型名称过长: %s", m)
  338. }
  339. }
  340. }
  341. // VertexAI 特殊校验
  342. if channel.Type == constant.ChannelTypeVertexAi {
  343. if channel.Other == "" {
  344. return fmt.Errorf("部署地区不能为空")
  345. }
  346. regionMap, err := common.StrToMap(channel.Other)
  347. if err != nil {
  348. return fmt.Errorf("部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}")
  349. }
  350. if regionMap["default"] == nil {
  351. return fmt.Errorf("部署地区必须包含default字段")
  352. }
  353. }
  354. return nil
  355. }
  356. type AddChannelRequest struct {
  357. Mode string `json:"mode"`
  358. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  359. Channel *model.Channel `json:"channel"`
  360. }
  361. func getVertexArrayKeys(keys string) ([]string, error) {
  362. if keys == "" {
  363. return nil, nil
  364. }
  365. var keyArray []interface{}
  366. err := common.Unmarshal([]byte(keys), &keyArray)
  367. if err != nil {
  368. return nil, fmt.Errorf("批量添加 Vertex AI 必须使用标准的JsonArray格式,例如[{key1}, {key2}...],请检查输入: %w", err)
  369. }
  370. cleanKeys := make([]string, 0, len(keyArray))
  371. for _, key := range keyArray {
  372. var keyStr string
  373. switch v := key.(type) {
  374. case string:
  375. keyStr = strings.TrimSpace(v)
  376. default:
  377. bytes, err := json.Marshal(v)
  378. if err != nil {
  379. return nil, fmt.Errorf("Vertex AI key JSON 编码失败: %w", err)
  380. }
  381. keyStr = string(bytes)
  382. }
  383. if keyStr != "" {
  384. cleanKeys = append(cleanKeys, keyStr)
  385. }
  386. }
  387. if len(cleanKeys) == 0 {
  388. return nil, fmt.Errorf("批量添加 Vertex AI 的 keys 不能为空")
  389. }
  390. return cleanKeys, nil
  391. }
  392. func AddChannel(c *gin.Context) {
  393. addChannelRequest := AddChannelRequest{}
  394. err := c.ShouldBindJSON(&addChannelRequest)
  395. if err != nil {
  396. common.ApiError(c, err)
  397. return
  398. }
  399. // 使用统一的校验函数
  400. if err := validateChannel(addChannelRequest.Channel, true); err != nil {
  401. c.JSON(http.StatusOK, gin.H{
  402. "success": false,
  403. "message": err.Error(),
  404. })
  405. return
  406. }
  407. addChannelRequest.Channel.CreatedTime = common.GetTimestamp()
  408. keys := make([]string, 0)
  409. switch addChannelRequest.Mode {
  410. case "multi_to_single":
  411. addChannelRequest.Channel.ChannelInfo.IsMultiKey = true
  412. addChannelRequest.Channel.ChannelInfo.MultiKeyMode = addChannelRequest.MultiKeyMode
  413. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  414. array, err := getVertexArrayKeys(addChannelRequest.Channel.Key)
  415. if err != nil {
  416. c.JSON(http.StatusOK, gin.H{
  417. "success": false,
  418. "message": err.Error(),
  419. })
  420. return
  421. }
  422. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(array)
  423. addChannelRequest.Channel.Key = strings.Join(array, "\n")
  424. } else {
  425. cleanKeys := make([]string, 0)
  426. for _, key := range strings.Split(addChannelRequest.Channel.Key, "\n") {
  427. if key == "" {
  428. continue
  429. }
  430. key = strings.TrimSpace(key)
  431. cleanKeys = append(cleanKeys, key)
  432. }
  433. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(cleanKeys)
  434. addChannelRequest.Channel.Key = strings.Join(cleanKeys, "\n")
  435. }
  436. keys = []string{addChannelRequest.Channel.Key}
  437. case "batch":
  438. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  439. // multi json
  440. keys, err = getVertexArrayKeys(addChannelRequest.Channel.Key)
  441. if err != nil {
  442. c.JSON(http.StatusOK, gin.H{
  443. "success": false,
  444. "message": err.Error(),
  445. })
  446. return
  447. }
  448. } else {
  449. keys = strings.Split(addChannelRequest.Channel.Key, "\n")
  450. }
  451. case "single":
  452. keys = []string{addChannelRequest.Channel.Key}
  453. default:
  454. c.JSON(http.StatusOK, gin.H{
  455. "success": false,
  456. "message": "不支持的添加模式",
  457. })
  458. return
  459. }
  460. channels := make([]model.Channel, 0, len(keys))
  461. for _, key := range keys {
  462. if key == "" {
  463. continue
  464. }
  465. localChannel := addChannelRequest.Channel
  466. localChannel.Key = key
  467. channels = append(channels, *localChannel)
  468. }
  469. err = model.BatchInsertChannels(channels)
  470. if err != nil {
  471. common.ApiError(c, err)
  472. return
  473. }
  474. c.JSON(http.StatusOK, gin.H{
  475. "success": true,
  476. "message": "",
  477. })
  478. return
  479. }
  480. func DeleteChannel(c *gin.Context) {
  481. id, _ := strconv.Atoi(c.Param("id"))
  482. channel := model.Channel{Id: id}
  483. err := channel.Delete()
  484. if err != nil {
  485. common.ApiError(c, err)
  486. return
  487. }
  488. c.JSON(http.StatusOK, gin.H{
  489. "success": true,
  490. "message": "",
  491. })
  492. return
  493. }
  494. func DeleteDisabledChannel(c *gin.Context) {
  495. rows, err := model.DeleteDisabledChannel()
  496. if err != nil {
  497. common.ApiError(c, err)
  498. return
  499. }
  500. c.JSON(http.StatusOK, gin.H{
  501. "success": true,
  502. "message": "",
  503. "data": rows,
  504. })
  505. return
  506. }
  507. type ChannelTag struct {
  508. Tag string `json:"tag"`
  509. NewTag *string `json:"new_tag"`
  510. Priority *int64 `json:"priority"`
  511. Weight *uint `json:"weight"`
  512. ModelMapping *string `json:"model_mapping"`
  513. Models *string `json:"models"`
  514. Groups *string `json:"groups"`
  515. }
  516. func DisableTagChannels(c *gin.Context) {
  517. channelTag := ChannelTag{}
  518. err := c.ShouldBindJSON(&channelTag)
  519. if err != nil || channelTag.Tag == "" {
  520. c.JSON(http.StatusOK, gin.H{
  521. "success": false,
  522. "message": "参数错误",
  523. })
  524. return
  525. }
  526. err = model.DisableChannelByTag(channelTag.Tag)
  527. if err != nil {
  528. common.ApiError(c, err)
  529. return
  530. }
  531. c.JSON(http.StatusOK, gin.H{
  532. "success": true,
  533. "message": "",
  534. })
  535. return
  536. }
  537. func EnableTagChannels(c *gin.Context) {
  538. channelTag := ChannelTag{}
  539. err := c.ShouldBindJSON(&channelTag)
  540. if err != nil || channelTag.Tag == "" {
  541. c.JSON(http.StatusOK, gin.H{
  542. "success": false,
  543. "message": "参数错误",
  544. })
  545. return
  546. }
  547. err = model.EnableChannelByTag(channelTag.Tag)
  548. if err != nil {
  549. common.ApiError(c, err)
  550. return
  551. }
  552. c.JSON(http.StatusOK, gin.H{
  553. "success": true,
  554. "message": "",
  555. })
  556. return
  557. }
  558. func EditTagChannels(c *gin.Context) {
  559. channelTag := ChannelTag{}
  560. err := c.ShouldBindJSON(&channelTag)
  561. if err != nil {
  562. c.JSON(http.StatusOK, gin.H{
  563. "success": false,
  564. "message": "参数错误",
  565. })
  566. return
  567. }
  568. if channelTag.Tag == "" {
  569. c.JSON(http.StatusOK, gin.H{
  570. "success": false,
  571. "message": "tag不能为空",
  572. })
  573. return
  574. }
  575. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  576. if err != nil {
  577. common.ApiError(c, err)
  578. return
  579. }
  580. c.JSON(http.StatusOK, gin.H{
  581. "success": true,
  582. "message": "",
  583. })
  584. return
  585. }
  586. type ChannelBatch struct {
  587. Ids []int `json:"ids"`
  588. Tag *string `json:"tag"`
  589. }
  590. func DeleteChannelBatch(c *gin.Context) {
  591. channelBatch := ChannelBatch{}
  592. err := c.ShouldBindJSON(&channelBatch)
  593. if err != nil || len(channelBatch.Ids) == 0 {
  594. c.JSON(http.StatusOK, gin.H{
  595. "success": false,
  596. "message": "参数错误",
  597. })
  598. return
  599. }
  600. err = model.BatchDeleteChannels(channelBatch.Ids)
  601. if err != nil {
  602. common.ApiError(c, err)
  603. return
  604. }
  605. c.JSON(http.StatusOK, gin.H{
  606. "success": true,
  607. "message": "",
  608. "data": len(channelBatch.Ids),
  609. })
  610. return
  611. }
  612. type PatchChannel struct {
  613. model.Channel
  614. MultiKeyMode *string `json:"multi_key_mode"`
  615. }
  616. func UpdateChannel(c *gin.Context) {
  617. channel := PatchChannel{}
  618. err := c.ShouldBindJSON(&channel)
  619. if err != nil {
  620. common.ApiError(c, err)
  621. return
  622. }
  623. // 使用统一的校验函数
  624. if err := validateChannel(&channel.Channel, false); err != nil {
  625. c.JSON(http.StatusOK, gin.H{
  626. "success": false,
  627. "message": err.Error(),
  628. })
  629. return
  630. }
  631. // Preserve existing ChannelInfo to ensure multi-key channels keep correct state even if the client does not send ChannelInfo in the request.
  632. originChannel, err := model.GetChannelById(channel.Id, false)
  633. if err != nil {
  634. c.JSON(http.StatusOK, gin.H{
  635. "success": false,
  636. "message": err.Error(),
  637. })
  638. return
  639. }
  640. // Always copy the original ChannelInfo so that fields like IsMultiKey and MultiKeySize are retained.
  641. channel.ChannelInfo = originChannel.ChannelInfo
  642. // If the request explicitly specifies a new MultiKeyMode, apply it on top of the original info.
  643. if channel.MultiKeyMode != nil && *channel.MultiKeyMode != "" {
  644. channel.ChannelInfo.MultiKeyMode = constant.MultiKeyMode(*channel.MultiKeyMode)
  645. }
  646. err = channel.Update()
  647. if err != nil {
  648. common.ApiError(c, err)
  649. return
  650. }
  651. if common.MemoryCacheEnabled {
  652. model.InitChannelCache()
  653. }
  654. channel.Key = ""
  655. c.JSON(http.StatusOK, gin.H{
  656. "success": true,
  657. "message": "",
  658. "data": channel,
  659. })
  660. return
  661. }
  662. func FetchModels(c *gin.Context) {
  663. var req struct {
  664. BaseURL string `json:"base_url"`
  665. Type int `json:"type"`
  666. Key string `json:"key"`
  667. }
  668. if err := c.ShouldBindJSON(&req); err != nil {
  669. c.JSON(http.StatusBadRequest, gin.H{
  670. "success": false,
  671. "message": "Invalid request",
  672. })
  673. return
  674. }
  675. baseURL := req.BaseURL
  676. if baseURL == "" {
  677. baseURL = constant.ChannelBaseURLs[req.Type]
  678. }
  679. client := &http.Client{}
  680. url := fmt.Sprintf("%s/v1/models", baseURL)
  681. request, err := http.NewRequest("GET", url, nil)
  682. if err != nil {
  683. c.JSON(http.StatusInternalServerError, gin.H{
  684. "success": false,
  685. "message": err.Error(),
  686. })
  687. return
  688. }
  689. // remove line breaks and extra spaces.
  690. key := strings.TrimSpace(req.Key)
  691. // If the key contains a line break, only take the first part.
  692. key = strings.Split(key, "\n")[0]
  693. request.Header.Set("Authorization", "Bearer "+key)
  694. response, err := client.Do(request)
  695. if err != nil {
  696. c.JSON(http.StatusInternalServerError, gin.H{
  697. "success": false,
  698. "message": err.Error(),
  699. })
  700. return
  701. }
  702. //check status code
  703. if response.StatusCode != http.StatusOK {
  704. c.JSON(http.StatusInternalServerError, gin.H{
  705. "success": false,
  706. "message": "Failed to fetch models",
  707. })
  708. return
  709. }
  710. defer response.Body.Close()
  711. var result struct {
  712. Data []struct {
  713. ID string `json:"id"`
  714. } `json:"data"`
  715. }
  716. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  717. c.JSON(http.StatusInternalServerError, gin.H{
  718. "success": false,
  719. "message": err.Error(),
  720. })
  721. return
  722. }
  723. var models []string
  724. for _, model := range result.Data {
  725. models = append(models, model.ID)
  726. }
  727. c.JSON(http.StatusOK, gin.H{
  728. "success": true,
  729. "data": models,
  730. })
  731. }
  732. func BatchSetChannelTag(c *gin.Context) {
  733. channelBatch := ChannelBatch{}
  734. err := c.ShouldBindJSON(&channelBatch)
  735. if err != nil || len(channelBatch.Ids) == 0 {
  736. c.JSON(http.StatusOK, gin.H{
  737. "success": false,
  738. "message": "参数错误",
  739. })
  740. return
  741. }
  742. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  743. if err != nil {
  744. common.ApiError(c, err)
  745. return
  746. }
  747. c.JSON(http.StatusOK, gin.H{
  748. "success": true,
  749. "message": "",
  750. "data": len(channelBatch.Ids),
  751. })
  752. return
  753. }
  754. func GetTagModels(c *gin.Context) {
  755. tag := c.Query("tag")
  756. if tag == "" {
  757. c.JSON(http.StatusBadRequest, gin.H{
  758. "success": false,
  759. "message": "tag不能为空",
  760. })
  761. return
  762. }
  763. channels, err := model.GetChannelsByTag(tag, false) // Assuming false for idSort is fine here
  764. if err != nil {
  765. c.JSON(http.StatusInternalServerError, gin.H{
  766. "success": false,
  767. "message": err.Error(),
  768. })
  769. return
  770. }
  771. var longestModels string
  772. maxLength := 0
  773. // Find the longest models string among all channels with the given tag
  774. for _, channel := range channels {
  775. if channel.Models != "" {
  776. currentModels := strings.Split(channel.Models, ",")
  777. if len(currentModels) > maxLength {
  778. maxLength = len(currentModels)
  779. longestModels = channel.Models
  780. }
  781. }
  782. }
  783. c.JSON(http.StatusOK, gin.H{
  784. "success": true,
  785. "message": "",
  786. "data": longestModels,
  787. })
  788. return
  789. }
  790. // CopyChannel handles cloning an existing channel with its key.
  791. // POST /api/channel/copy/:id
  792. // Optional query params:
  793. //
  794. // suffix - string appended to the original name (default "_复制")
  795. // reset_balance - bool, when true will reset balance & used_quota to 0 (default true)
  796. func CopyChannel(c *gin.Context) {
  797. id, err := strconv.Atoi(c.Param("id"))
  798. if err != nil {
  799. c.JSON(http.StatusOK, gin.H{"success": false, "message": "invalid id"})
  800. return
  801. }
  802. suffix := c.DefaultQuery("suffix", "_复制")
  803. resetBalance := true
  804. if rbStr := c.DefaultQuery("reset_balance", "true"); rbStr != "" {
  805. if v, err := strconv.ParseBool(rbStr); err == nil {
  806. resetBalance = v
  807. }
  808. }
  809. // fetch original channel with key
  810. origin, err := model.GetChannelById(id, true)
  811. if err != nil {
  812. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  813. return
  814. }
  815. // clone channel
  816. clone := *origin // shallow copy is sufficient as we will overwrite primitives
  817. clone.Id = 0 // let DB auto-generate
  818. clone.CreatedTime = common.GetTimestamp()
  819. clone.Name = origin.Name + suffix
  820. clone.TestTime = 0
  821. clone.ResponseTime = 0
  822. if resetBalance {
  823. clone.Balance = 0
  824. clone.UsedQuota = 0
  825. }
  826. // insert
  827. if err := model.BatchInsertChannels([]model.Channel{clone}); err != nil {
  828. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  829. return
  830. }
  831. // success
  832. c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": gin.H{"id": clone.Id}})
  833. }