setting.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. package service
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/mhsanaei/3x-ui/v2/database"
  12. "github.com/mhsanaei/3x-ui/v2/database/model"
  13. "github.com/mhsanaei/3x-ui/v2/logger"
  14. "github.com/mhsanaei/3x-ui/v2/util/common"
  15. "github.com/mhsanaei/3x-ui/v2/util/random"
  16. "github.com/mhsanaei/3x-ui/v2/util/reflect_util"
  17. "github.com/mhsanaei/3x-ui/v2/web/entity"
  18. "github.com/mhsanaei/3x-ui/v2/xray"
  19. )
  20. //go:embed config.json
  21. var xrayTemplateConfig string
  22. var defaultValueMap = map[string]string{
  23. "xrayTemplateConfig": xrayTemplateConfig,
  24. "webListen": "",
  25. "webDomain": "",
  26. "webPort": "2053",
  27. "webCertFile": "",
  28. "webKeyFile": "",
  29. "secret": random.Seq(32),
  30. "webBasePath": "/",
  31. "sessionMaxAge": "360",
  32. "pageSize": "50",
  33. "expireDiff": "0",
  34. "trafficDiff": "0",
  35. "remarkModel": "-ieo",
  36. "timeLocation": "Local",
  37. "tgBotEnable": "false",
  38. "tgBotToken": "",
  39. "tgBotProxy": "",
  40. "tgBotAPIServer": "",
  41. "tgBotChatId": "",
  42. "tgRunTime": "@daily",
  43. "tgBotBackup": "false",
  44. "tgBotLoginNotify": "true",
  45. "tgCpu": "80",
  46. "tgLang": "en-US",
  47. "twoFactorEnable": "false",
  48. "twoFactorToken": "",
  49. "subEnable": "true",
  50. "subJsonEnable": "false",
  51. "subTitle": "",
  52. "subListen": "",
  53. "subPort": "2096",
  54. "subPath": "/sub/",
  55. "subDomain": "",
  56. "subCertFile": "",
  57. "subKeyFile": "",
  58. "subUpdates": "12",
  59. "subEncrypt": "true",
  60. "subShowInfo": "true",
  61. "subURI": "",
  62. "subJsonPath": "/json/",
  63. "subJsonURI": "",
  64. "subJsonFragment": "",
  65. "subJsonNoises": "",
  66. "subJsonMux": "",
  67. "subJsonRules": "",
  68. "datepicker": "gregorian",
  69. "warp": "",
  70. "externalTrafficInformEnable": "false",
  71. "externalTrafficInformURI": "",
  72. }
  73. // SettingService provides business logic for application settings management.
  74. // It handles configuration storage, retrieval, and validation for all system settings.
  75. type SettingService struct{}
  76. func (s *SettingService) GetDefaultJsonConfig() (any, error) {
  77. var jsonData any
  78. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  79. if err != nil {
  80. return nil, err
  81. }
  82. return jsonData, nil
  83. }
  84. func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
  85. db := database.GetDB()
  86. settings := make([]*model.Setting, 0)
  87. err := db.Model(model.Setting{}).Not("key = ?", "xrayTemplateConfig").Find(&settings).Error
  88. if err != nil {
  89. return nil, err
  90. }
  91. allSetting := &entity.AllSetting{}
  92. t := reflect.TypeOf(allSetting).Elem()
  93. v := reflect.ValueOf(allSetting).Elem()
  94. fields := reflect_util.GetFields(t)
  95. setSetting := func(key, value string) (err error) {
  96. defer func() {
  97. panicErr := recover()
  98. if panicErr != nil {
  99. err = errors.New(fmt.Sprint(panicErr))
  100. }
  101. }()
  102. var found bool
  103. var field reflect.StructField
  104. for _, f := range fields {
  105. if f.Tag.Get("json") == key {
  106. field = f
  107. found = true
  108. break
  109. }
  110. }
  111. if !found {
  112. // Some settings are automatically generated, no need to return to the front end to modify the user
  113. return nil
  114. }
  115. fieldV := v.FieldByName(field.Name)
  116. switch t := fieldV.Interface().(type) {
  117. case int:
  118. n, err := strconv.ParseInt(value, 10, 64)
  119. if err != nil {
  120. return err
  121. }
  122. fieldV.SetInt(n)
  123. case string:
  124. fieldV.SetString(value)
  125. case bool:
  126. fieldV.SetBool(value == "true")
  127. default:
  128. return common.NewErrorf("unknown field %v type %v", key, t)
  129. }
  130. return
  131. }
  132. keyMap := map[string]bool{}
  133. for _, setting := range settings {
  134. err := setSetting(setting.Key, setting.Value)
  135. if err != nil {
  136. return nil, err
  137. }
  138. keyMap[setting.Key] = true
  139. }
  140. for key, value := range defaultValueMap {
  141. if keyMap[key] {
  142. continue
  143. }
  144. err := setSetting(key, value)
  145. if err != nil {
  146. return nil, err
  147. }
  148. }
  149. return allSetting, nil
  150. }
  151. func (s *SettingService) ResetSettings() error {
  152. db := database.GetDB()
  153. err := db.Where("1 = 1").Delete(model.Setting{}).Error
  154. if err != nil {
  155. return err
  156. }
  157. return db.Model(model.User{}).
  158. Where("1 = 1").Error
  159. }
  160. func (s *SettingService) getSetting(key string) (*model.Setting, error) {
  161. db := database.GetDB()
  162. setting := &model.Setting{}
  163. err := db.Model(model.Setting{}).Where("key = ?", key).First(setting).Error
  164. if err != nil {
  165. return nil, err
  166. }
  167. return setting, nil
  168. }
  169. func (s *SettingService) saveSetting(key string, value string) error {
  170. setting, err := s.getSetting(key)
  171. db := database.GetDB()
  172. if database.IsNotFound(err) {
  173. return db.Create(&model.Setting{
  174. Key: key,
  175. Value: value,
  176. }).Error
  177. } else if err != nil {
  178. return err
  179. }
  180. setting.Key = key
  181. setting.Value = value
  182. return db.Save(setting).Error
  183. }
  184. func (s *SettingService) getString(key string) (string, error) {
  185. setting, err := s.getSetting(key)
  186. if database.IsNotFound(err) {
  187. value, ok := defaultValueMap[key]
  188. if !ok {
  189. return "", common.NewErrorf("key <%v> not in defaultValueMap", key)
  190. }
  191. return value, nil
  192. } else if err != nil {
  193. return "", err
  194. }
  195. return setting.Value, nil
  196. }
  197. func (s *SettingService) setString(key string, value string) error {
  198. return s.saveSetting(key, value)
  199. }
  200. func (s *SettingService) getBool(key string) (bool, error) {
  201. str, err := s.getString(key)
  202. if err != nil {
  203. return false, err
  204. }
  205. return strconv.ParseBool(str)
  206. }
  207. func (s *SettingService) setBool(key string, value bool) error {
  208. return s.setString(key, strconv.FormatBool(value))
  209. }
  210. func (s *SettingService) getInt(key string) (int, error) {
  211. str, err := s.getString(key)
  212. if err != nil {
  213. return 0, err
  214. }
  215. return strconv.Atoi(str)
  216. }
  217. func (s *SettingService) setInt(key string, value int) error {
  218. return s.setString(key, strconv.Itoa(value))
  219. }
  220. func (s *SettingService) GetXrayConfigTemplate() (string, error) {
  221. return s.getString("xrayTemplateConfig")
  222. }
  223. func (s *SettingService) GetListen() (string, error) {
  224. return s.getString("webListen")
  225. }
  226. func (s *SettingService) SetListen(ip string) error {
  227. return s.setString("webListen", ip)
  228. }
  229. func (s *SettingService) GetWebDomain() (string, error) {
  230. return s.getString("webDomain")
  231. }
  232. func (s *SettingService) GetTgBotToken() (string, error) {
  233. return s.getString("tgBotToken")
  234. }
  235. func (s *SettingService) SetTgBotToken(token string) error {
  236. return s.setString("tgBotToken", token)
  237. }
  238. func (s *SettingService) GetTgBotProxy() (string, error) {
  239. return s.getString("tgBotProxy")
  240. }
  241. func (s *SettingService) SetTgBotProxy(token string) error {
  242. return s.setString("tgBotProxy", token)
  243. }
  244. func (s *SettingService) GetTgBotAPIServer() (string, error) {
  245. return s.getString("tgBotAPIServer")
  246. }
  247. func (s *SettingService) SetTgBotAPIServer(token string) error {
  248. return s.setString("tgBotAPIServer", token)
  249. }
  250. func (s *SettingService) GetTgBotChatId() (string, error) {
  251. return s.getString("tgBotChatId")
  252. }
  253. func (s *SettingService) SetTgBotChatId(chatIds string) error {
  254. return s.setString("tgBotChatId", chatIds)
  255. }
  256. func (s *SettingService) GetTgbotEnabled() (bool, error) {
  257. return s.getBool("tgBotEnable")
  258. }
  259. func (s *SettingService) SetTgbotEnabled(value bool) error {
  260. return s.setBool("tgBotEnable", value)
  261. }
  262. func (s *SettingService) GetTgbotRuntime() (string, error) {
  263. return s.getString("tgRunTime")
  264. }
  265. func (s *SettingService) SetTgbotRuntime(time string) error {
  266. return s.setString("tgRunTime", time)
  267. }
  268. func (s *SettingService) GetTgBotBackup() (bool, error) {
  269. return s.getBool("tgBotBackup")
  270. }
  271. func (s *SettingService) GetTgBotLoginNotify() (bool, error) {
  272. return s.getBool("tgBotLoginNotify")
  273. }
  274. func (s *SettingService) GetTgCpu() (int, error) {
  275. return s.getInt("tgCpu")
  276. }
  277. func (s *SettingService) GetTgLang() (string, error) {
  278. return s.getString("tgLang")
  279. }
  280. func (s *SettingService) GetTwoFactorEnable() (bool, error) {
  281. return s.getBool("twoFactorEnable")
  282. }
  283. func (s *SettingService) SetTwoFactorEnable(value bool) error {
  284. return s.setBool("twoFactorEnable", value)
  285. }
  286. func (s *SettingService) GetTwoFactorToken() (string, error) {
  287. return s.getString("twoFactorToken")
  288. }
  289. func (s *SettingService) SetTwoFactorToken(value string) error {
  290. return s.setString("twoFactorToken", value)
  291. }
  292. func (s *SettingService) GetPort() (int, error) {
  293. return s.getInt("webPort")
  294. }
  295. func (s *SettingService) SetPort(port int) error {
  296. return s.setInt("webPort", port)
  297. }
  298. func (s *SettingService) SetCertFile(webCertFile string) error {
  299. return s.setString("webCertFile", webCertFile)
  300. }
  301. func (s *SettingService) GetCertFile() (string, error) {
  302. return s.getString("webCertFile")
  303. }
  304. func (s *SettingService) SetKeyFile(webKeyFile string) error {
  305. return s.setString("webKeyFile", webKeyFile)
  306. }
  307. func (s *SettingService) GetKeyFile() (string, error) {
  308. return s.getString("webKeyFile")
  309. }
  310. func (s *SettingService) GetExpireDiff() (int, error) {
  311. return s.getInt("expireDiff")
  312. }
  313. func (s *SettingService) GetTrafficDiff() (int, error) {
  314. return s.getInt("trafficDiff")
  315. }
  316. func (s *SettingService) GetSessionMaxAge() (int, error) {
  317. return s.getInt("sessionMaxAge")
  318. }
  319. func (s *SettingService) GetRemarkModel() (string, error) {
  320. return s.getString("remarkModel")
  321. }
  322. func (s *SettingService) GetSecret() ([]byte, error) {
  323. secret, err := s.getString("secret")
  324. if secret == defaultValueMap["secret"] {
  325. err := s.saveSetting("secret", secret)
  326. if err != nil {
  327. logger.Warning("save secret failed:", err)
  328. }
  329. }
  330. return []byte(secret), err
  331. }
  332. func (s *SettingService) SetBasePath(basePath string) error {
  333. if !strings.HasPrefix(basePath, "/") {
  334. basePath = "/" + basePath
  335. }
  336. if !strings.HasSuffix(basePath, "/") {
  337. basePath += "/"
  338. }
  339. return s.setString("webBasePath", basePath)
  340. }
  341. func (s *SettingService) GetBasePath() (string, error) {
  342. basePath, err := s.getString("webBasePath")
  343. if err != nil {
  344. return "", err
  345. }
  346. if !strings.HasPrefix(basePath, "/") {
  347. basePath = "/" + basePath
  348. }
  349. if !strings.HasSuffix(basePath, "/") {
  350. basePath += "/"
  351. }
  352. return basePath, nil
  353. }
  354. func (s *SettingService) GetTimeLocation() (*time.Location, error) {
  355. l, err := s.getString("timeLocation")
  356. if err != nil {
  357. return nil, err
  358. }
  359. location, err := time.LoadLocation(l)
  360. if err != nil {
  361. defaultLocation := defaultValueMap["timeLocation"]
  362. logger.Errorf("location <%v> not exist, using default location: %v", l, defaultLocation)
  363. return time.LoadLocation(defaultLocation)
  364. }
  365. return location, nil
  366. }
  367. func (s *SettingService) GetSubEnable() (bool, error) {
  368. return s.getBool("subEnable")
  369. }
  370. func (s *SettingService) GetSubJsonEnable() (bool, error) {
  371. return s.getBool("subJsonEnable")
  372. }
  373. func (s *SettingService) GetSubTitle() (string, error) {
  374. return s.getString("subTitle")
  375. }
  376. func (s *SettingService) GetSubListen() (string, error) {
  377. return s.getString("subListen")
  378. }
  379. func (s *SettingService) GetSubPort() (int, error) {
  380. return s.getInt("subPort")
  381. }
  382. func (s *SettingService) GetSubPath() (string, error) {
  383. return s.getString("subPath")
  384. }
  385. func (s *SettingService) GetSubJsonPath() (string, error) {
  386. return s.getString("subJsonPath")
  387. }
  388. func (s *SettingService) GetSubDomain() (string, error) {
  389. return s.getString("subDomain")
  390. }
  391. func (s *SettingService) GetSubCertFile() (string, error) {
  392. return s.getString("subCertFile")
  393. }
  394. func (s *SettingService) GetSubKeyFile() (string, error) {
  395. return s.getString("subKeyFile")
  396. }
  397. func (s *SettingService) GetSubUpdates() (string, error) {
  398. return s.getString("subUpdates")
  399. }
  400. func (s *SettingService) GetSubEncrypt() (bool, error) {
  401. return s.getBool("subEncrypt")
  402. }
  403. func (s *SettingService) GetSubShowInfo() (bool, error) {
  404. return s.getBool("subShowInfo")
  405. }
  406. func (s *SettingService) GetPageSize() (int, error) {
  407. return s.getInt("pageSize")
  408. }
  409. func (s *SettingService) GetSubURI() (string, error) {
  410. return s.getString("subURI")
  411. }
  412. func (s *SettingService) GetSubJsonURI() (string, error) {
  413. return s.getString("subJsonURI")
  414. }
  415. func (s *SettingService) GetSubJsonFragment() (string, error) {
  416. return s.getString("subJsonFragment")
  417. }
  418. func (s *SettingService) GetSubJsonNoises() (string, error) {
  419. return s.getString("subJsonNoises")
  420. }
  421. func (s *SettingService) GetSubJsonMux() (string, error) {
  422. return s.getString("subJsonMux")
  423. }
  424. func (s *SettingService) GetSubJsonRules() (string, error) {
  425. return s.getString("subJsonRules")
  426. }
  427. func (s *SettingService) GetDatepicker() (string, error) {
  428. return s.getString("datepicker")
  429. }
  430. func (s *SettingService) GetWarp() (string, error) {
  431. return s.getString("warp")
  432. }
  433. func (s *SettingService) SetWarp(data string) error {
  434. return s.setString("warp", data)
  435. }
  436. func (s *SettingService) GetExternalTrafficInformEnable() (bool, error) {
  437. return s.getBool("externalTrafficInformEnable")
  438. }
  439. func (s *SettingService) SetExternalTrafficInformEnable(value bool) error {
  440. return s.setBool("externalTrafficInformEnable", value)
  441. }
  442. func (s *SettingService) GetExternalTrafficInformURI() (string, error) {
  443. return s.getString("externalTrafficInformURI")
  444. }
  445. func (s *SettingService) SetExternalTrafficInformURI(InformURI string) error {
  446. return s.setString("externalTrafficInformURI", InformURI)
  447. }
  448. func (s *SettingService) GetIpLimitEnable() (bool, error) {
  449. accessLogPath, err := xray.GetAccessLogPath()
  450. if err != nil {
  451. return false, err
  452. }
  453. return (accessLogPath != "none" && accessLogPath != ""), nil
  454. }
  455. func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error {
  456. if err := allSetting.CheckValid(); err != nil {
  457. return err
  458. }
  459. v := reflect.ValueOf(allSetting).Elem()
  460. t := reflect.TypeOf(allSetting).Elem()
  461. fields := reflect_util.GetFields(t)
  462. errs := make([]error, 0)
  463. for _, field := range fields {
  464. key := field.Tag.Get("json")
  465. fieldV := v.FieldByName(field.Name)
  466. value := fmt.Sprint(fieldV.Interface())
  467. err := s.saveSetting(key, value)
  468. if err != nil {
  469. errs = append(errs, err)
  470. }
  471. }
  472. return common.Combine(errs...)
  473. }
  474. func (s *SettingService) GetDefaultXrayConfig() (any, error) {
  475. var jsonData any
  476. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  477. if err != nil {
  478. return nil, err
  479. }
  480. return jsonData, nil
  481. }
  482. func (s *SettingService) GetDefaultSettings(host string) (any, error) {
  483. type settingFunc func() (any, error)
  484. settings := map[string]settingFunc{
  485. "expireDiff": func() (any, error) { return s.GetExpireDiff() },
  486. "trafficDiff": func() (any, error) { return s.GetTrafficDiff() },
  487. "pageSize": func() (any, error) { return s.GetPageSize() },
  488. "defaultCert": func() (any, error) { return s.GetCertFile() },
  489. "defaultKey": func() (any, error) { return s.GetKeyFile() },
  490. "tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
  491. "subEnable": func() (any, error) { return s.GetSubEnable() },
  492. "subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
  493. "subTitle": func() (any, error) { return s.GetSubTitle() },
  494. "subURI": func() (any, error) { return s.GetSubURI() },
  495. "subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
  496. "remarkModel": func() (any, error) { return s.GetRemarkModel() },
  497. "datepicker": func() (any, error) { return s.GetDatepicker() },
  498. "ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
  499. }
  500. result := make(map[string]any)
  501. for key, fn := range settings {
  502. value, err := fn()
  503. if err != nil {
  504. return "", err
  505. }
  506. result[key] = value
  507. }
  508. subEnable := result["subEnable"].(bool)
  509. subJsonEnable := false
  510. if v, ok := result["subJsonEnable"]; ok {
  511. if b, ok2 := v.(bool); ok2 {
  512. subJsonEnable = b
  513. }
  514. }
  515. if (subEnable && result["subURI"].(string) == "") || (subJsonEnable && result["subJsonURI"].(string) == "") {
  516. subURI := ""
  517. subTitle, _ := s.GetSubTitle()
  518. subPort, _ := s.GetSubPort()
  519. subPath, _ := s.GetSubPath()
  520. subJsonPath, _ := s.GetSubJsonPath()
  521. subDomain, _ := s.GetSubDomain()
  522. subKeyFile, _ := s.GetSubKeyFile()
  523. subCertFile, _ := s.GetSubCertFile()
  524. subTLS := false
  525. if subKeyFile != "" && subCertFile != "" {
  526. subTLS = true
  527. }
  528. if subDomain == "" {
  529. subDomain = strings.Split(host, ":")[0]
  530. }
  531. if subTLS {
  532. subURI = "https://"
  533. } else {
  534. subURI = "http://"
  535. }
  536. if (subPort == 443 && subTLS) || (subPort == 80 && !subTLS) {
  537. subURI += subDomain
  538. } else {
  539. subURI += fmt.Sprintf("%s:%d", subDomain, subPort)
  540. }
  541. if subEnable && result["subURI"].(string) == "" {
  542. result["subURI"] = subURI + subPath
  543. }
  544. if result["subTitle"].(string) == "" {
  545. result["subTitle"] = subTitle
  546. }
  547. if subJsonEnable && result["subJsonURI"].(string) == "" {
  548. result["subJsonURI"] = subURI + subJsonPath
  549. }
  550. }
  551. return result, nil
  552. }