option.go 16 KB

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