1
0

setting.go 15 KB

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