option.go 16 KB

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