setting.go 16 KB

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