setting.go 13 KB

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