option.go 16 KB

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