setting.go 9.8 KB

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