option.go 15 KB

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