Skip to content

Commit 73c3d2a

Browse files
committed
Update
1 parent 6ca0c50 commit 73c3d2a

File tree

4 files changed

+123
-162
lines changed

4 files changed

+123
-162
lines changed

.github/workflows/release.yml

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
name: Build Sync-Configuration
2+
3+
on:
4+
push:
5+
tags:
6+
- "v*"
7+
8+
jobs:
9+
Build:
10+
permissions: write-all
11+
runs-on: ubuntu-latest
12+
env:
13+
APP_NAME: GUI-Sync
14+
steps:
15+
- uses: actions/checkout@v4
16+
- name: Set up Go
17+
uses: actions/setup-go@v5
18+
with:
19+
go-version-file: ./go.mod
20+
21+
- name: Build 1
22+
run: GOOS=windows GOARCH=amd64 go build -o ${{ env.APP_NAME }}-windows-amd64.exe
23+
24+
- name: Build 2
25+
run: GOOS=windows GOARCH=arm64 go build -o ${{ env.APP_NAME }}-windows-arm64.exe
26+
27+
- name: Build 3
28+
run: GOOS=windows GOARCH=386 go build -o ${{ env.APP_NAME }}-windows-386.exe
29+
30+
- name: Build 4
31+
run: GOOS=linux GOARCH=amd64 go build -o ${{ env.APP_NAME }}-linux-amd64
32+
33+
- name: Build 5
34+
run: GOOS=linux GOARCH=arm64 go build -o ${{ env.APP_NAME }}-linux-arm64
35+
36+
- name: Create Release and Upload Assets
37+
uses: svenstaro/upload-release-action@v2
38+
with:
39+
repo_token: ${{ secrets.GITHUB_TOKEN }}
40+
file: ${{ env.APP_NAME }}*
41+
tag: ${{ github.ref }}
42+
overwrite: true
43+
file_glob: true

.gitignore

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
data
2-
backup_index.json
3-
sync_configuration.exe
2+
GUI-Sync

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module sync_configuration
22

3-
go 1.22.1
3+
go 1.21.10

main.go

Lines changed: 78 additions & 159 deletions
Original file line numberDiff line numberDiff line change
@@ -8,62 +8,45 @@ import (
88
"net/http"
99
"os"
1010
"path"
11-
"path/filepath"
1211
"strings"
1312
)
1413

1514
var (
16-
backupIndexFile = "backup_index.json"
17-
dataDir = "data"
18-
backupIndex []BackupEntry
19-
addrss = "0.0.0.0"
20-
port = 8080
21-
token = ""
15+
SavePath = "data"
16+
Addrss = "0.0.0.0"
17+
Port = 8080
18+
Token = ""
2219
)
2320

2421
type BackupEntry struct {
25-
Id string `json:"id"`
26-
Files []string `json:"files"`
22+
Id string `json:"id"`
23+
Tag string `json:"tag"`
24+
Files map[string]string `json:"files"`
2725
}
2826

2927
func main() {
30-
31-
flag.StringVar(&token, "token", "", "Authorization")
32-
flag.StringVar(&addrss, "address", "0.0.0.0", "Address to listen on")
33-
flag.IntVar(&port, "port", 8080, "Port to listen on")
28+
flag.StringVar(&Token, "token", "", "Authorization")
29+
flag.StringVar(&Addrss, "address", "0.0.0.0", "Address to listen on")
30+
flag.IntVar(&Port, "port", 8080, "Port to listen on")
3431
flag.Parse()
3532

36-
if token == "" {
33+
if Token == "" {
3734
fmt.Println("You need to specify a token that is the same as the client")
3835
return
3936
}
4037

41-
loadBackupIndex()
38+
os.MkdirAll(SavePath, os.ModePerm)
4239

4340
http.HandleFunc("/backup", withAuth(handleBackup))
44-
http.HandleFunc("/file", withAuth(handleFile))
45-
http.ListenAndServe(fmt.Sprintf("%s:%d", addrss, port), nil)
46-
}
47-
48-
func loadBackupIndex() {
49-
file, err := os.ReadFile(backupIndexFile)
50-
if err != nil {
51-
log.Printf("Error reading backup index file: %v\n", err)
52-
return
53-
}
54-
55-
err = json.Unmarshal(file, &backupIndex)
56-
if err != nil {
57-
log.Printf("Error decoding backup index JSON: %v\n", err)
58-
return
59-
}
41+
http.HandleFunc("/sync", withAuth(handleSync))
42+
http.ListenAndServe(fmt.Sprintf("%s:%d", Addrss, Port), nil)
6043
}
6144

6245
func withAuth(next http.HandlerFunc) http.HandlerFunc {
6346
return func(w http.ResponseWriter, r *http.Request) {
6447
authHeader := r.Header.Get("Authorization")
6548
uaHeader := r.Header.Get("User-Agent")
66-
if uaHeader != "GUI.for.Cores" || authHeader != "Bearer "+token {
49+
if uaHeader != "GUI.for.Cores" || authHeader != "Bearer "+Token {
6750
http.Error(w, "Unauthorized", http.StatusUnauthorized)
6851
return
6952
}
@@ -74,182 +57,118 @@ func withAuth(next http.HandlerFunc) http.HandlerFunc {
7457
func handleBackup(w http.ResponseWriter, r *http.Request) {
7558
switch r.Method {
7659
case http.MethodGet:
77-
idParam := r.URL.Query().Get("id")
60+
tag := r.URL.Query().Get("tag")
61+
p := path.Join(SavePath, tag)
7862

79-
log.Printf("List => %s\n", idParam)
63+
log.Printf("List => where tag = %s\n", tag)
8064

81-
var response []byte
82-
result := make([]string, 0)
65+
if !strings.HasPrefix(path.Clean(p), SavePath) {
66+
http.Error(w, "403", http.StatusForbidden)
67+
return
68+
}
8369

84-
if idParam != "" {
85-
for _, entry := range backupIndex {
86-
if entry.Id == idParam {
87-
result = entry.Files
88-
break
89-
}
90-
}
70+
dirs, err := os.ReadDir(p)
71+
if err != nil {
72+
http.Error(w, err.Error(), http.StatusInternalServerError)
73+
return
74+
}
9175

92-
var err error
93-
response, err = json.Marshal(result)
94-
if err != nil {
95-
http.Error(w, "Failed to marshal JSON response", http.StatusInternalServerError)
96-
return
97-
}
98-
} else {
99-
for _, entry := range backupIndex {
100-
result = append(result, entry.Id)
76+
result := make([]string, 0)
77+
for _, file := range dirs {
78+
if !file.IsDir() {
79+
result = append(result, file.Name())
10180
}
81+
}
10282

103-
var err error
104-
response, err = json.Marshal(result)
105-
if err != nil {
106-
http.Error(w, "Failed to marshal JSON response", http.StatusInternalServerError)
107-
return
108-
}
83+
response, err := json.Marshal(result)
84+
if err != nil {
85+
http.Error(w, err.Error(), http.StatusInternalServerError)
86+
return
10987
}
11088

11189
w.Header().Set("Content-Type", "application/json")
11290
w.WriteHeader(http.StatusOK)
11391
w.Write(response)
11492

11593
case http.MethodDelete:
94+
tag := r.URL.Query().Get("tag")
11695
ids := r.URL.Query().Get("ids")
11796

118-
if ids == "" {
119-
http.Error(w, "Error parameter", http.StatusBadRequest)
120-
return
121-
}
122-
97+
p := path.Join(SavePath, tag)
12398
idsToDelete := strings.Split(ids, ",")
12499

125-
log.Printf("Remove => %s\n", ids)
126-
127-
updatedBackupIndex := make([]BackupEntry, 0)
100+
log.Printf("Remove => where tag = %s and id in %s\n", tag, ids)
128101

129-
for _, entry := range backupIndex {
130-
found := false
131-
for _, id := range idsToDelete {
132-
if entry.Id == id {
133-
found = true
134-
break
135-
}
136-
}
137-
if !found {
138-
updatedBackupIndex = append(updatedBackupIndex, entry)
139-
} else {
140-
filePath := filepath.Join(dataDir, entry.Id)
141-
os.RemoveAll(filePath)
142-
}
143-
}
144-
145-
backupIndex = updatedBackupIndex
146-
147-
updateBackupIndexFile()
148-
149-
default:
150-
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
151-
}
152-
}
153-
154-
func handleFile(w http.ResponseWriter, r *http.Request) {
155-
switch r.Method {
156-
case http.MethodGet:
157-
pathParam := r.URL.Query().Get("path")
158-
159-
_path := path.Clean(path.Join(dataDir, pathParam))
160-
if !strings.HasPrefix(_path, dataDir) {
161-
w.WriteHeader(http.StatusBadRequest)
102+
if !strings.HasPrefix(path.Clean(p), SavePath) {
103+
http.Error(w, "403", http.StatusForbidden)
162104
return
163105
}
164106

165-
log.Printf("Sync : %v\n", pathParam)
166-
167-
body, err := os.ReadFile(_path)
168-
if err != nil {
169-
w.WriteHeader(http.StatusNotFound)
170-
return
107+
for _, id := range idsToDelete {
108+
os.RemoveAll(path.Join(p, id))
171109
}
172110

173-
w.Header().Set("Content-Type", "text/plain")
174111
w.WriteHeader(http.StatusOK)
175-
w.Write(body)
176112

177113
case http.MethodPost:
178-
var requestBody map[string]string
179-
err := json.NewDecoder(r.Body).Decode(&requestBody)
114+
var body BackupEntry
115+
err := json.NewDecoder(r.Body).Decode(&body)
180116
if err != nil {
181-
http.Error(w, "Failed to parse request body", http.StatusBadRequest)
117+
http.Error(w, err.Error(), http.StatusBadRequest)
182118
return
183119
}
184120

185-
id := requestBody["id"]
186-
filename := requestBody["file"]
187-
fileContent := requestBody["body"]
121+
p := path.Join(SavePath, body.Tag, body.Id)
188122

189-
log.Printf("Backup : %v => %v\n", id, filename)
123+
log.Printf("Backup : id = %s, tag = %s, files.length = %v\n", body.Id, body.Tag, len(body.Files))
190124

191-
filePath := filepath.Join(dataDir, id, filename)
192-
err = os.MkdirAll(filepath.Dir(filePath), 0755)
193-
if err != nil {
194-
http.Error(w, "Failed to create directory", http.StatusInternalServerError)
125+
if !strings.HasPrefix(path.Clean(p), SavePath) {
126+
http.Error(w, "403", http.StatusForbidden)
195127
return
196128
}
197129

198-
err = os.WriteFile(filePath, []byte(fileContent), 0644)
130+
b, err := json.Marshal(body)
199131
if err != nil {
200-
http.Error(w, "Failed to write file", http.StatusInternalServerError)
132+
log.Printf("Backup err %v", err.Error())
133+
http.Error(w, err.Error(), http.StatusBadRequest)
201134
return
202135
}
203136

204-
updateBackupIndex(id, filename)
137+
os.MkdirAll(path.Join(SavePath, body.Tag), os.ModePerm)
138+
139+
os.WriteFile(p+".json", b, 0644)
205140

206141
w.WriteHeader(http.StatusCreated)
142+
207143
default:
208144
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
209145
}
210146
}
211147

212-
func updateBackupIndex(id, filename string) {
213-
var found bool
214-
for i, entry := range backupIndex {
215-
if entry.Id == id {
216-
// Check if file already exists in the list
217-
found = true
218-
foundFile := false
219-
for _, file := range entry.Files {
220-
if file == filename {
221-
foundFile = true
222-
break
223-
}
224-
}
225-
// If file not found, append to the list
226-
if !foundFile {
227-
backupIndex[i].Files = append(backupIndex[i].Files, filename)
228-
}
229-
break
148+
func handleSync(w http.ResponseWriter, r *http.Request) {
149+
switch r.Method {
150+
case http.MethodGet:
151+
tag := r.URL.Query().Get("tag")
152+
id := r.URL.Query().Get("id")
153+
154+
p := path.Join(SavePath, tag, id)
155+
156+
if !strings.HasPrefix(p, SavePath) {
157+
http.Error(w, "403", http.StatusForbidden)
158+
return
230159
}
231-
}
232-
if !found {
233-
backupIndex = append(backupIndex, BackupEntry{
234-
Id: id,
235-
Files: []string{filename},
236-
})
237-
}
238160

239-
updateBackupIndexFile()
240-
}
161+
b, err := os.ReadFile(p)
162+
if err != nil {
163+
http.Error(w, "403", http.StatusForbidden)
164+
return
165+
}
241166

242-
func updateBackupIndexFile() {
243-
// Update backup index file
244-
jsonData, err := json.MarshalIndent(backupIndex, "", " ")
245-
if err != nil {
246-
log.Printf("Error marshaling backup index JSON: %v\n", err)
247-
return
248-
}
167+
w.Header().Set("Content-Type", "application/json")
168+
w.WriteHeader(http.StatusOK)
169+
w.Write(b)
249170

250-
err = os.WriteFile(backupIndexFile, jsonData, 0644)
251-
if err != nil {
252-
log.Printf("Error writing backup index file: %v\n", err)
253-
return
171+
default:
172+
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
254173
}
255174
}

0 commit comments

Comments
 (0)