setting.go 13 KB

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