option.go 17 KB

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