setting.go 14 KB

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