Skip to content

Commit

Permalink
[refactor] string values to json
Browse files Browse the repository at this point in the history
  • Loading branch information
alireza0 committed Jun 6, 2024
1 parent c994f4b commit 2cabf0a
Show file tree
Hide file tree
Showing 12 changed files with 121 additions and 138 deletions.
13 changes: 8 additions & 5 deletions backend/api/api.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package api

import (
"fmt"
"s-ui/logger"
"s-ui/service"
"strconv"
Expand Down Expand Up @@ -157,8 +156,8 @@ func (a *APIHandler) getHandler(c *gin.Context) {
}
}

func (a *APIHandler) loadData(c *gin.Context) (string, error) {
var data string
func (a *APIHandler) loadData(c *gin.Context) (interface{}, error) {
data := make(map[string]interface{}, 0)
lu := c.Query("lu")
isUpdated, err := a.ConfigService.CheckChanges(lu)
if err != nil {
Expand All @@ -185,9 +184,13 @@ func (a *APIHandler) loadData(c *gin.Context) (string, error) {
if err != nil {
return "", err
}
data = fmt.Sprintf(`{"config": %s, "clients": %s, "tls": %s, "subURI": "%s", "onlines": %s}`, string(*config), clients, tlsConfigs, subURI, onlines)
data["config"] = *config
data["clients"] = clients
data["tls"] = tlsConfigs
data["subURI"] = subURI
data["onlines"] = onlines
} else {
data = fmt.Sprintf(`{"onlines": %s}`, onlines)
data["onlines"] = onlines
}

return data, nil
Expand Down
22 changes: 11 additions & 11 deletions backend/database/model/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,17 @@ type User struct {
}

type Client struct {
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Enable bool `json:"enable" form:"enable"`
Name string `json:"name" form:"name"`
Config string `json:"config" form:"config"`
Inbounds string `json:"inbounds" form:"inbounds"`
Links string `json:"links" form:"links"`
Volume int64 `json:"volume" form:"volume"`
Expiry int64 `json:"expiry" form:"expiry"`
Down int64 `json:"down" form:"down"`
Up int64 `json:"up" form:"up"`
Desc string `json:"desc" from:"desc"`
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Enable bool `json:"enable" form:"enable"`
Name string `json:"name" form:"name"`
Config json.RawMessage `json:"config" form:"config"`
Inbounds json.RawMessage `json:"inbounds" form:"inbounds"`
Links json.RawMessage `json:"links" form:"links"`
Volume int64 `json:"volume" form:"volume"`
Expiry int64 `json:"expiry" form:"expiry"`
Down int64 `json:"down" form:"down"`
Up int64 `json:"up" form:"up"`
Desc string `json:"desc" from:"desc"`
}

type Stats struct {
Expand Down
18 changes: 8 additions & 10 deletions backend/service/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"s-ui/database"
"s-ui/database/model"
"s-ui/logger"
"strings"
"time"

"gorm.io/gorm"
Expand All @@ -14,18 +13,14 @@ import (
type ClientService struct {
}

func (s *ClientService) GetAll() (string, error) {
func (s *ClientService) GetAll() ([]model.Client, error) {
db := database.GetDB()
clients := []model.Client{}
err := db.Model(model.Client{}).Scan(&clients).Error
if err != nil {
return "", err
return nil, err
}
data, err := json.Marshal(clients)
if err != nil {
return "", err
}
return string(data), nil
return clients, nil
}

func (s *ClientService) Save(tx *gorm.DB, changes []model.Changes) error {
Expand Down Expand Up @@ -62,14 +57,16 @@ func (s *ClientService) DepleteClients() ([]string, []string, error) {
return nil, nil, err
}

dt := time.Now().Unix()
var users, inbounds []string
for _, client := range clients {
logger.Debug("Client ", client.Name, " is going to be disabled")
users = append(users, client.Name)
userInbounds := strings.Split(client.Inbounds, ",")
var userInbounds []string
json.Unmarshal(client.Inbounds, &userInbounds)
inbounds = append(inbounds, userInbounds...)
changes = append(changes, model.Changes{
DateTime: time.Now().Unix(),
DateTime: dt,
Actor: "DepleteJob",
Key: "clients",
Action: "disable",
Expand All @@ -87,6 +84,7 @@ func (s *ClientService) DepleteClients() ([]string, []string, error) {
if err != nil {
return nil, nil, err
}
LastUpdate = dt
}

return users, inbounds, nil
Expand Down
69 changes: 32 additions & 37 deletions backend/service/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,27 @@ func (s *ConfigService) InitConfig() error {
return err
}
}
return s.RefreshApiAddr(&data)
var singboxConfig SingBoxConfig
err = json.Unmarshal(data, &singboxConfig)
if err != nil {
return err
}

return s.RefreshApiAddr(&singboxConfig)
}

func (s *ConfigService) GetConfig() (*[]byte, error) {
func (s *ConfigService) GetConfig() (*SingBoxConfig, error) {
configPath := config.GetBinFolderPath()
data, err := os.ReadFile(configPath + "/config.json")
if err != nil {
return nil, err
}
return &data, nil
singboxConfig := SingBoxConfig{}
err = json.Unmarshal(data, &singboxConfig)
if err != nil {
return nil, err
}
return &singboxConfig, nil
}

func (s *ConfigService) SaveChanges(changes map[string]string, loginUser string) error {
Expand Down Expand Up @@ -127,11 +138,7 @@ func (s *ConfigService) SaveChanges(changes map[string]string, loginUser string)
if err != nil {
return err
}
newConfig := SingBoxConfig{}
err = json.Unmarshal(*singboxConfig, &newConfig)
if err != nil {
return err
}
newConfig := *singboxConfig
for _, change := range configChanges {
rawObject := change.Obj
switch change.Key {
Expand Down Expand Up @@ -169,12 +176,7 @@ func (s *ConfigService) SaveChanges(changes map[string]string, loginUser string)
}
}

// Save to config.json
data, err := json.MarshalIndent(newConfig, "", " ")
if err != nil {
return err
}
err = s.Save(&data)
err = s.Save(&newConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -215,7 +217,7 @@ func (s *ConfigService) CheckChanges(lu string) (bool, error) {
}
}

func (s *ConfigService) Save(data *[]byte) error {
func (s *ConfigService) Save(singboxConfig *SingBoxConfig) error {
configPath := config.GetBinFolderPath()
_, err := os.Stat(configPath + "/config.json")
if os.IsNotExist(err) {
Expand All @@ -227,35 +229,36 @@ func (s *ConfigService) Save(data *[]byte) error {
return err
}

err = os.WriteFile(configPath+"/config.json", *data, 0764)
data, err := json.MarshalIndent(singboxConfig, " ", " ")
if err != nil {
return err
}

err = os.WriteFile(configPath+"/config.json", data, 0764)
if err != nil {
return err
}

s.RefreshApiAddr(data)
s.RefreshApiAddr(singboxConfig)
s.Controller.Restart()

return nil
}

func (s *ConfigService) RefreshApiAddr(data *[]byte) error {
func (s *ConfigService) RefreshApiAddr(singboxConfig *SingBoxConfig) error {
Env_API := config.GetEnvApi()
if len(Env_API) > 0 {
ApiAddr = Env_API
} else {
var err error
if data == nil {
data, err = s.GetConfig()
if singboxConfig == nil {
singboxConfig, err = s.GetConfig()
if err != nil {
return err
}
}

singboxConfig := SingBoxConfig{}
err = json.Unmarshal(*data, &singboxConfig)
if err != nil {
return err
}

var experimental struct {
V2rayApi struct {
Listen string `json:"listen"`
Expand All @@ -282,12 +285,7 @@ func (s *ConfigService) DepleteClients() error {
if err != nil {
return err
}
newConfig := SingBoxConfig{}
err = json.Unmarshal(*singboxConfig, &newConfig)
if err != nil {
return err
}
for inbound_index, inbound := range newConfig.Inbounds {
for inbound_index, inbound := range singboxConfig.Inbounds {
var inboundJson map[string]interface{}
json.Unmarshal(inbound, &inboundJson)
if s.contains(inbounds, inboundJson["tag"].(string)) {
Expand Down Expand Up @@ -326,13 +324,10 @@ func (s *ConfigService) DepleteClients() error {
if err != nil {
return err
}
newConfig.Inbounds[inbound_index] = modifiedInbound
singboxConfig.Inbounds[inbound_index] = modifiedInbound
}
modifiedConfig, err := json.MarshalIndent(newConfig, "", " ")
if err != nil {
return err
}
err = s.Save(&modifiedConfig)

err = s.Save(singboxConfig)
if err != nil {
return err
}
Expand Down
9 changes: 2 additions & 7 deletions backend/service/stats.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package service

import (
"encoding/json"
"s-ui/database"
"s-ui/database/model"
"time"
Expand Down Expand Up @@ -86,12 +85,8 @@ func (s *StatsService) GetStats(resorce string, tag string, limit int) ([]model.
return result, nil
}

func (s *StatsService) GetOnlines() (string, error) {
onlines, err := json.Marshal(onlineResources)
if err != nil {
return "", err
}
return string(onlines), nil
func (s *StatsService) GetOnlines() (onlines, error) {
return *onlineResources, nil
}
func (s *StatsService) DelOldStats(days int) error {
oldTime := time.Now().AddDate(0, 0, -(days)).Unix()
Expand Down
11 changes: 4 additions & 7 deletions backend/service/tls.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,15 @@ import (
type TlsService struct {
}

func (s *TlsService) GetAll() (string, error) {
func (s *TlsService) GetAll() ([]model.Tls, error) {
db := database.GetDB()
tlsConfig := []model.Tls{}
err := db.Model(model.Tls{}).Scan(&tlsConfig).Error
if err != nil {
return "", err
return nil, err
}
data, err := json.Marshal(tlsConfig)
if err != nil {
return "", err
}
return string(data), nil

return tlsConfig, nil
}

func (s *TlsService) Save(tx *gorm.DB, changes []model.Changes) error {
Expand Down
23 changes: 11 additions & 12 deletions frontend/src/layouts/modals/Client.vue
Original file line number Diff line number Diff line change
Expand Up @@ -179,18 +179,17 @@ export default {
const newData = JSON.parse(this.$props.data)
this.client = createClient(newData)
this.title = "edit"
this.clientConfig = JSON.parse(this.client.config)
this.clientConfig = this.client.config
}
else {
this.client = createClient()
this.title = "add"
this.clientConfig = randomConfigs('client')
}
this.clientStats = this.$props.stats
const allLinks = <Link[]>JSON.parse(this.client.links)
this.links = allLinks.filter(l => l.type == 'local')
this.extLinks = allLinks.filter(l => l.type == 'external')
this.subLinks = allLinks.filter(l => l.type == 'sub')
this.links = this.client.links.filter(l => l.type == 'local')
this.extLinks = this.client.links.filter(l => l.type == 'external')
this.subLinks = this.client.links.filter(l => l.type == 'sub')
this.tab = "t1"
},
closeModal() {
Expand All @@ -199,11 +198,11 @@ export default {
},
saveChanges() {
this.loading = true
this.client.config = updateConfigs(JSON.stringify(this.clientConfig), this.client.name)
this.client.links = JSON.stringify([
...this.links,
...this.extLinks.filter(l => l.uri != ''),
...this.subLinks.filter(l => l.uri != '')])
this.client.config = updateConfigs(this.clientConfig, this.client.name)
this.client.links = [
...this.links,
...this.extLinks.filter(l => l.uri != ''),
...this.subLinks.filter(l => l.uri != '')]
this.$emit('save', this.client, this.clientStats)
this.loading = false
},
Expand All @@ -213,8 +212,8 @@ export default {
},
computed: {
clientInbounds: {
get() { return this.client.inbounds == "" ? [] : this.client.inbounds.split(',').filter(i => this.inboundTags.includes(i)) },
set(newValue:string[]) { this.client.inbounds = newValue.length == 0 ? "" : newValue.join(',') }
get() { return this.client.inbounds.length>0 ? this.client.inbounds.filter(i => this.inboundTags.includes(i)) : [] },
set(newValue:string[]) { this.client.inbounds = newValue.length == 0 ? [] : newValue }
},
expDate: {
get() { return this.client.expiry},
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/store/modules/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@ const Data = defineStore('Data', {
this.lastLoad = Math.floor((new Date()).getTime()/1000)

// Set new data
const data = JSON.parse(msg.obj)
const data = JSON.parse(JSON.stringify(msg.obj))
if (data.subURI) this.subURI = data.subURI
if (data.config) this.config = data.config
if (data.clients) this.clients = data.clients
if (data.tls) this.tlsConfigs = data.tls
this.onlines = data.onlines

// To avoid ref copy
if (data.config) this.oldData.config = { ...JSON.parse(msg.obj).config }
if (data.clients) this.oldData.clients = [ ...JSON.parse(msg.obj).clients ]
if (data.tls) this.oldData.tlsConfigs = [ ...JSON.parse(msg.obj).tls ]
if (data.config) this.oldData.config = { ...msg.obj }.config
if (data.clients) this.oldData.clients = { ...msg.obj }.clients
if (data.tls) this.oldData.tlsConfigs = { ...msg.obj }.tls
}
},
async pushData() {
Expand Down
Loading

0 comments on commit 2cabf0a

Please sign in to comment.