option.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. package model
  2. import (
  3. "one-api/common"
  4. "one-api/setting"
  5. "one-api/setting/config"
  6. "one-api/setting/operation_setting"
  7. "strconv"
  8. "strings"
  9. "time"
  10. )
  11. type Option struct {
  12. Key string `json:"key" gorm:"primaryKey"`
  13. Value string `json:"value"`
  14. }
  15. func AllOption() ([]*Option, error) {
  16. var options []*Option
  17. var err error
  18. err = DB.Find(&options).Error
  19. return options, err
  20. }
  21. func InitOptionMap() {
  22. common.OptionMapRWMutex.Lock()
  23. common.OptionMap = make(map[string]string)
  24. // 添加原有的系统配置
  25. common.OptionMap["FileUploadPermission"] = strconv.Itoa(common.FileUploadPermission)
  26. common.OptionMap["FileDownloadPermission"] = strconv.Itoa(common.FileDownloadPermission)
  27. common.OptionMap["ImageUploadPermission"] = strconv.Itoa(common.ImageUploadPermission)
  28. common.OptionMap["ImageDownloadPermission"] = strconv.Itoa(common.ImageDownloadPermission)
  29. common.OptionMap["PasswordLoginEnabled"] = strconv.FormatBool(common.PasswordLoginEnabled)
  30. common.OptionMap["PasswordRegisterEnabled"] = strconv.FormatBool(common.PasswordRegisterEnabled)
  31. common.OptionMap["EmailVerificationEnabled"] = strconv.FormatBool(common.EmailVerificationEnabled)
  32. common.OptionMap["GitHubOAuthEnabled"] = strconv.FormatBool(common.GitHubOAuthEnabled)
  33. common.OptionMap["LinuxDOOAuthEnabled"] = strconv.FormatBool(common.LinuxDOOAuthEnabled)
  34. common.OptionMap["TelegramOAuthEnabled"] = strconv.FormatBool(common.TelegramOAuthEnabled)
  35. common.OptionMap["WeChatAuthEnabled"] = strconv.FormatBool(common.WeChatAuthEnabled)
  36. common.OptionMap["TurnstileCheckEnabled"] = strconv.FormatBool(common.TurnstileCheckEnabled)
  37. common.OptionMap["RegisterEnabled"] = strconv.FormatBool(common.RegisterEnabled)
  38. common.OptionMap["AutomaticDisableChannelEnabled"] = strconv.FormatBool(common.AutomaticDisableChannelEnabled)
  39. common.OptionMap["AutomaticEnableChannelEnabled"] = strconv.FormatBool(common.AutomaticEnableChannelEnabled)
  40. common.OptionMap["LogConsumeEnabled"] = strconv.FormatBool(common.LogConsumeEnabled)
  41. common.OptionMap["DisplayInCurrencyEnabled"] = strconv.FormatBool(common.DisplayInCurrencyEnabled)
  42. common.OptionMap["DisplayTokenStatEnabled"] = strconv.FormatBool(common.DisplayTokenStatEnabled)
  43. common.OptionMap["DrawingEnabled"] = strconv.FormatBool(common.DrawingEnabled)
  44. common.OptionMap["TaskEnabled"] = strconv.FormatBool(common.TaskEnabled)
  45. common.OptionMap["DataExportEnabled"] = strconv.FormatBool(common.DataExportEnabled)
  46. common.OptionMap["ChannelDisableThreshold"] = strconv.FormatFloat(common.ChannelDisableThreshold, 'f', -1, 64)
  47. common.OptionMap["EmailDomainRestrictionEnabled"] = strconv.FormatBool(common.EmailDomainRestrictionEnabled)
  48. common.OptionMap["EmailAliasRestrictionEnabled"] = strconv.FormatBool(common.EmailAliasRestrictionEnabled)
  49. common.OptionMap["EmailDomainWhitelist"] = strings.Join(common.EmailDomainWhitelist, ",")
  50. common.OptionMap["SMTPServer"] = ""
  51. common.OptionMap["SMTPFrom"] = ""
  52. common.OptionMap["SMTPPort"] = strconv.Itoa(common.SMTPPort)
  53. common.OptionMap["SMTPAccount"] = ""
  54. common.OptionMap["SMTPToken"] = ""
  55. common.OptionMap["SMTPSSLEnabled"] = strconv.FormatBool(common.SMTPSSLEnabled)
  56. common.OptionMap["Notice"] = ""
  57. common.OptionMap["About"] = ""
  58. common.OptionMap["HomePageContent"] = ""
  59. common.OptionMap["Footer"] = common.Footer
  60. common.OptionMap["SystemName"] = common.SystemName
  61. common.OptionMap["Logo"] = common.Logo
  62. common.OptionMap["ServerAddress"] = ""
  63. common.OptionMap["WorkerUrl"] = setting.WorkerUrl
  64. common.OptionMap["WorkerValidKey"] = setting.WorkerValidKey
  65. common.OptionMap["PayAddress"] = ""
  66. common.OptionMap["CustomCallbackAddress"] = ""
  67. common.OptionMap["EpayId"] = ""
  68. common.OptionMap["EpayKey"] = ""
  69. common.OptionMap["Price"] = strconv.FormatFloat(setting.Price, 'f', -1, 64)
  70. common.OptionMap["MinTopUp"] = strconv.Itoa(setting.MinTopUp)
  71. common.OptionMap["TopupGroupRatio"] = common.TopupGroupRatio2JSONString()
  72. common.OptionMap["Chats"] = setting.Chats2JsonString()
  73. common.OptionMap["GitHubClientId"] = ""
  74. common.OptionMap["GitHubClientSecret"] = ""
  75. common.OptionMap["TelegramBotToken"] = ""
  76. common.OptionMap["TelegramBotName"] = ""
  77. common.OptionMap["WeChatServerAddress"] = ""
  78. common.OptionMap["WeChatServerToken"] = ""
  79. common.OptionMap["WeChatAccountQRCodeImageURL"] = ""
  80. common.OptionMap["TurnstileSiteKey"] = ""
  81. common.OptionMap["TurnstileSecretKey"] = ""
  82. common.OptionMap["QuotaForNewUser"] = strconv.Itoa(common.QuotaForNewUser)
  83. common.OptionMap["QuotaForInviter"] = strconv.Itoa(common.QuotaForInviter)
  84. common.OptionMap["QuotaForInvitee"] = strconv.Itoa(common.QuotaForInvitee)
  85. common.OptionMap["QuotaRemindThreshold"] = strconv.Itoa(common.QuotaRemindThreshold)
  86. common.OptionMap["PreConsumedQuota"] = strconv.Itoa(common.PreConsumedQuota)
  87. common.OptionMap["ModelRequestRateLimitCount"] = strconv.Itoa(setting.ModelRequestRateLimitCount)
  88. common.OptionMap["ModelRequestRateLimitDurationMinutes"] = strconv.Itoa(setting.ModelRequestRateLimitDurationMinutes)
  89. common.OptionMap["ModelRequestRateLimitSuccessCount"] = strconv.Itoa(setting.ModelRequestRateLimitSuccessCount)
  90. common.OptionMap["ModelRequestRateLimitGroup"] = setting.ModelRequestRateLimitGroup2JSONString()
  91. common.OptionMap["ModelRatio"] = operation_setting.ModelRatio2JSONString()
  92. common.OptionMap["ModelPrice"] = operation_setting.ModelPrice2JSONString()
  93. common.OptionMap["CacheRatio"] = operation_setting.CacheRatio2JSONString()
  94. common.OptionMap["GroupRatio"] = setting.GroupRatio2JSONString()
  95. common.OptionMap["UserUsableGroups"] = setting.UserUsableGroups2JSONString()
  96. common.OptionMap["CompletionRatio"] = operation_setting.CompletionRatio2JSONString()
  97. common.OptionMap["TopUpLink"] = common.TopUpLink
  98. //common.OptionMap["ChatLink"] = common.ChatLink
  99. //common.OptionMap["ChatLink2"] = common.ChatLink2
  100. common.OptionMap["QuotaPerUnit"] = strconv.FormatFloat(common.QuotaPerUnit, 'f', -1, 64)
  101. common.OptionMap["RetryTimes"] = strconv.Itoa(common.RetryTimes)
  102. common.OptionMap["DataExportInterval"] = strconv.Itoa(common.DataExportInterval)
  103. common.OptionMap["DataExportDefaultTime"] = common.DataExportDefaultTime
  104. common.OptionMap["DefaultCollapseSidebar"] = strconv.FormatBool(common.DefaultCollapseSidebar)
  105. common.OptionMap["MjNotifyEnabled"] = strconv.FormatBool(setting.MjNotifyEnabled)
  106. common.OptionMap["MjAccountFilterEnabled"] = strconv.FormatBool(setting.MjAccountFilterEnabled)
  107. common.OptionMap["MjModeClearEnabled"] = strconv.FormatBool(setting.MjModeClearEnabled)
  108. common.OptionMap["MjForwardUrlEnabled"] = strconv.FormatBool(setting.MjForwardUrlEnabled)
  109. common.OptionMap["MjActionCheckSuccessEnabled"] = strconv.FormatBool(setting.MjActionCheckSuccessEnabled)
  110. common.OptionMap["CheckSensitiveEnabled"] = strconv.FormatBool(setting.CheckSensitiveEnabled)
  111. common.OptionMap["DemoSiteEnabled"] = strconv.FormatBool(operation_setting.DemoSiteEnabled)
  112. common.OptionMap["SelfUseModeEnabled"] = strconv.FormatBool(operation_setting.SelfUseModeEnabled)
  113. common.OptionMap["ModelRequestRateLimitEnabled"] = strconv.FormatBool(setting.ModelRequestRateLimitEnabled)
  114. common.OptionMap["CheckSensitiveOnPromptEnabled"] = strconv.FormatBool(setting.CheckSensitiveOnPromptEnabled)
  115. common.OptionMap["StopOnSensitiveEnabled"] = strconv.FormatBool(setting.StopOnSensitiveEnabled)
  116. common.OptionMap["SensitiveWords"] = setting.SensitiveWordsToString()
  117. common.OptionMap["StreamCacheQueueLength"] = strconv.Itoa(setting.StreamCacheQueueLength)
  118. common.OptionMap["AutomaticDisableKeywords"] = operation_setting.AutomaticDisableKeywordsToString()
  119. // 自动添加所有注册的模型配置
  120. modelConfigs := config.GlobalConfig.ExportAllConfigs()
  121. for k, v := range modelConfigs {
  122. common.OptionMap[k] = v
  123. }
  124. common.OptionMapRWMutex.Unlock()
  125. loadOptionsFromDatabase()
  126. }
  127. func loadOptionsFromDatabase() {
  128. options, _ := AllOption()
  129. for _, option := range options {
  130. err := updateOptionMap(option.Key, option.Value)
  131. if err != nil {
  132. common.SysError("failed to update option map: " + err.Error())
  133. }
  134. }
  135. }
  136. func SyncOptions(frequency int) {
  137. for {
  138. time.Sleep(time.Duration(frequency) * time.Second)
  139. common.SysLog("syncing options from database")
  140. loadOptionsFromDatabase()
  141. }
  142. }
  143. func UpdateOption(key string, value string) error {
  144. // Save to database first
  145. option := Option{
  146. Key: key,
  147. }
  148. // https://gorm.io/docs/update.html#Save-All-Fields
  149. DB.FirstOrCreate(&option, Option{Key: key})
  150. option.Value = value
  151. // Save is a combination function.
  152. // If save value does not contain primary key, it will execute Create,
  153. // otherwise it will execute Update (with all fields).
  154. DB.Save(&option)
  155. // Update OptionMap
  156. return updateOptionMap(key, value)
  157. }
  158. func updateOptionMap(key string, value string) (err error) {
  159. common.OptionMapRWMutex.Lock()
  160. defer common.OptionMapRWMutex.Unlock()
  161. common.OptionMap[key] = value
  162. // 检查是否是模型配置 - 使用更规范的方式处理
  163. if handleConfigUpdate(key, value) {
  164. return nil // 已由配置系统处理
  165. }
  166. // 处理传统配置项...
  167. if strings.HasSuffix(key, "Permission") {
  168. intValue, _ := strconv.Atoi(value)
  169. switch key {
  170. case "FileUploadPermission":
  171. common.FileUploadPermission = intValue
  172. case "FileDownloadPermission":
  173. common.FileDownloadPermission = intValue
  174. case "ImageUploadPermission":
  175. common.ImageUploadPermission = intValue
  176. case "ImageDownloadPermission":
  177. common.ImageDownloadPermission = intValue
  178. }
  179. }
  180. if strings.HasSuffix(key, "Enabled") || key == "DefaultCollapseSidebar" {
  181. boolValue := value == "true"
  182. switch key {
  183. case "PasswordRegisterEnabled":
  184. common.PasswordRegisterEnabled = boolValue
  185. case "PasswordLoginEnabled":
  186. common.PasswordLoginEnabled = boolValue
  187. case "EmailVerificationEnabled":
  188. common.EmailVerificationEnabled = boolValue
  189. case "GitHubOAuthEnabled":
  190. common.GitHubOAuthEnabled = boolValue
  191. case "LinuxDOOAuthEnabled":
  192. common.LinuxDOOAuthEnabled = boolValue
  193. case "WeChatAuthEnabled":
  194. common.WeChatAuthEnabled = boolValue
  195. case "TelegramOAuthEnabled":
  196. common.TelegramOAuthEnabled = boolValue
  197. case "TurnstileCheckEnabled":
  198. common.TurnstileCheckEnabled = boolValue
  199. case "RegisterEnabled":
  200. common.RegisterEnabled = boolValue
  201. case "EmailDomainRestrictionEnabled":
  202. common.EmailDomainRestrictionEnabled = boolValue
  203. case "EmailAliasRestrictionEnabled":
  204. common.EmailAliasRestrictionEnabled = boolValue
  205. case "AutomaticDisableChannelEnabled":
  206. common.AutomaticDisableChannelEnabled = boolValue
  207. case "AutomaticEnableChannelEnabled":
  208. common.AutomaticEnableChannelEnabled = boolValue
  209. case "LogConsumeEnabled":
  210. common.LogConsumeEnabled = boolValue
  211. case "DisplayInCurrencyEnabled":
  212. common.DisplayInCurrencyEnabled = boolValue
  213. case "DisplayTokenStatEnabled":
  214. common.DisplayTokenStatEnabled = boolValue
  215. case "DrawingEnabled":
  216. common.DrawingEnabled = boolValue
  217. case "TaskEnabled":
  218. common.TaskEnabled = boolValue
  219. case "DataExportEnabled":
  220. common.DataExportEnabled = boolValue
  221. case "DefaultCollapseSidebar":
  222. common.DefaultCollapseSidebar = boolValue
  223. case "MjNotifyEnabled":
  224. setting.MjNotifyEnabled = boolValue
  225. case "MjAccountFilterEnabled":
  226. setting.MjAccountFilterEnabled = boolValue
  227. case "MjModeClearEnabled":
  228. setting.MjModeClearEnabled = boolValue
  229. case "MjForwardUrlEnabled":
  230. setting.MjForwardUrlEnabled = boolValue
  231. case "MjActionCheckSuccessEnabled":
  232. setting.MjActionCheckSuccessEnabled = boolValue
  233. case "CheckSensitiveEnabled":
  234. setting.CheckSensitiveEnabled = boolValue
  235. case "DemoSiteEnabled":
  236. operation_setting.DemoSiteEnabled = boolValue
  237. case "SelfUseModeEnabled":
  238. operation_setting.SelfUseModeEnabled = boolValue
  239. case "CheckSensitiveOnPromptEnabled":
  240. setting.CheckSensitiveOnPromptEnabled = boolValue
  241. case "ModelRequestRateLimitEnabled":
  242. setting.ModelRequestRateLimitEnabled = boolValue
  243. case "StopOnSensitiveEnabled":
  244. setting.StopOnSensitiveEnabled = boolValue
  245. case "SMTPSSLEnabled":
  246. common.SMTPSSLEnabled = boolValue
  247. }
  248. }
  249. switch key {
  250. case "EmailDomainWhitelist":
  251. common.EmailDomainWhitelist = strings.Split(value, ",")
  252. case "SMTPServer":
  253. common.SMTPServer = value
  254. case "SMTPPort":
  255. intValue, _ := strconv.Atoi(value)
  256. common.SMTPPort = intValue
  257. case "SMTPAccount":
  258. common.SMTPAccount = value
  259. case "SMTPFrom":
  260. common.SMTPFrom = value
  261. case "SMTPToken":
  262. common.SMTPToken = value
  263. case "ServerAddress":
  264. setting.ServerAddress = value
  265. case "WorkerUrl":
  266. setting.WorkerUrl = value
  267. case "WorkerValidKey":
  268. setting.WorkerValidKey = value
  269. case "PayAddress":
  270. setting.PayAddress = value
  271. case "Chats":
  272. err = setting.UpdateChatsByJsonString(value)
  273. case "CustomCallbackAddress":
  274. setting.CustomCallbackAddress = value
  275. case "EpayId":
  276. setting.EpayId = value
  277. case "EpayKey":
  278. setting.EpayKey = value
  279. case "Price":
  280. setting.Price, _ = strconv.ParseFloat(value, 64)
  281. case "MinTopUp":
  282. setting.MinTopUp, _ = strconv.Atoi(value)
  283. case "TopupGroupRatio":
  284. err = common.UpdateTopupGroupRatioByJSONString(value)
  285. case "GitHubClientId":
  286. common.GitHubClientId = value
  287. case "GitHubClientSecret":
  288. common.GitHubClientSecret = value
  289. case "LinuxDOClientId":
  290. common.LinuxDOClientId = value
  291. case "LinuxDOClientSecret":
  292. common.LinuxDOClientSecret = value
  293. case "Footer":
  294. common.Footer = value
  295. case "SystemName":
  296. common.SystemName = value
  297. case "Logo":
  298. common.Logo = value
  299. case "WeChatServerAddress":
  300. common.WeChatServerAddress = value
  301. case "WeChatServerToken":
  302. common.WeChatServerToken = value
  303. case "WeChatAccountQRCodeImageURL":
  304. common.WeChatAccountQRCodeImageURL = value
  305. case "TelegramBotToken":
  306. common.TelegramBotToken = value
  307. case "TelegramBotName":
  308. common.TelegramBotName = value
  309. case "TurnstileSiteKey":
  310. common.TurnstileSiteKey = value
  311. case "TurnstileSecretKey":
  312. common.TurnstileSecretKey = value
  313. case "QuotaForNewUser":
  314. common.QuotaForNewUser, _ = strconv.Atoi(value)
  315. case "QuotaForInviter":
  316. common.QuotaForInviter, _ = strconv.Atoi(value)
  317. case "QuotaForInvitee":
  318. common.QuotaForInvitee, _ = strconv.Atoi(value)
  319. case "QuotaRemindThreshold":
  320. common.QuotaRemindThreshold, _ = strconv.Atoi(value)
  321. case "PreConsumedQuota":
  322. common.PreConsumedQuota, _ = strconv.Atoi(value)
  323. case "ModelRequestRateLimitCount":
  324. setting.ModelRequestRateLimitCount, _ = strconv.Atoi(value)
  325. case "ModelRequestRateLimitDurationMinutes":
  326. setting.ModelRequestRateLimitDurationMinutes, _ = strconv.Atoi(value)
  327. case "ModelRequestRateLimitSuccessCount":
  328. setting.ModelRequestRateLimitSuccessCount, _ = strconv.Atoi(value)
  329. case "ModelRequestRateLimitGroup":
  330. err = setting.UpdateModelRequestRateLimitGroupByJSONString(value)
  331. case "RetryTimes":
  332. common.RetryTimes, _ = strconv.Atoi(value)
  333. case "DataExportInterval":
  334. common.DataExportInterval, _ = strconv.Atoi(value)
  335. case "DataExportDefaultTime":
  336. common.DataExportDefaultTime = value
  337. case "ModelRatio":
  338. err = operation_setting.UpdateModelRatioByJSONString(value)
  339. case "GroupRatio":
  340. err = setting.UpdateGroupRatioByJSONString(value)
  341. case "UserUsableGroups":
  342. err = setting.UpdateUserUsableGroupsByJSONString(value)
  343. case "CompletionRatio":
  344. err = operation_setting.UpdateCompletionRatioByJSONString(value)
  345. case "ModelPrice":
  346. err = operation_setting.UpdateModelPriceByJSONString(value)
  347. case "CacheRatio":
  348. err = operation_setting.UpdateCacheRatioByJSONString(value)
  349. case "TopUpLink":
  350. common.TopUpLink = value
  351. //case "ChatLink":
  352. // common.ChatLink = value
  353. //case "ChatLink2":
  354. // common.ChatLink2 = value
  355. case "ChannelDisableThreshold":
  356. common.ChannelDisableThreshold, _ = strconv.ParseFloat(value, 64)
  357. case "QuotaPerUnit":
  358. common.QuotaPerUnit, _ = strconv.ParseFloat(value, 64)
  359. case "SensitiveWords":
  360. setting.SensitiveWordsFromString(value)
  361. case "AutomaticDisableKeywords":
  362. operation_setting.AutomaticDisableKeywordsFromString(value)
  363. case "StreamCacheQueueLength":
  364. setting.StreamCacheQueueLength, _ = strconv.Atoi(value)
  365. }
  366. return err
  367. }
  368. // handleConfigUpdate 处理分层配置更新,返回是否已处理
  369. func handleConfigUpdate(key, value string) bool {
  370. parts := strings.SplitN(key, ".", 2)
  371. if len(parts) != 2 {
  372. return false // 不是分层配置
  373. }
  374. configName := parts[0]
  375. configKey := parts[1]
  376. // 获取配置对象
  377. cfg := config.GlobalConfig.Get(configName)
  378. if cfg == nil {
  379. return false // 未注册的配置
  380. }
  381. // 更新配置
  382. configMap := map[string]string{
  383. configKey: value,
  384. }
  385. config.UpdateConfigFromMap(cfg, configMap)
  386. return true // 已处理
  387. }