option.go 17 KB

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