option.go 17 KB

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