1
0

setting.go 14 KB

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