setting.go 9.5 KB

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