-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
279 lines (246 loc) · 9.62 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package main
import (
"cloud.google.com/go/firestore"
"context"
firebase "firebase.google.com/go"
"firebase.google.com/go/storage"
"fmt"
"golang.org/x/crypto/acme/autocert"
"io"
"log"
"net/http"
"os"
"path/filepath"
"remap-keys.app/remap-build-server/auth"
"remap-keys.app/remap-build-server/build"
"remap-keys.app/remap-build-server/database"
"remap-keys.app/remap-build-server/parameter"
"remap-keys.app/remap-build-server/web"
)
func main() {
// Prepare the Firestore firestoreClient.
ctx := context.Background()
app := createFirebaseApp(ctx)
firestoreClient, err := app.Firestore(ctx)
if err != nil {
log.Fatalln(err)
}
defer firestoreClient.Close()
storageClient, err := app.Storage(ctx)
if err != nil {
log.Fatalln(err)
}
certCache := web.NewFirestoreCertCache(firestoreClient)
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: certCache,
HostPolicy: autocert.HostWhitelist("build.remap-keys.app"),
}
http.HandleFunc("/build", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
handleRequest(w, r, ctx, firestoreClient, storageClient)
} else {
http.NotFound(w, r)
}
})
server := &http.Server{
Addr: ":https",
TLSConfig: certManager.TLSConfig(),
Handler: nil,
}
log.Printf("[Info] Listening on port 443")
log.Fatal(server.ListenAndServeTLS("", ""))
//port := "8080"
//h := func(w http.ResponseWriter, r *http.Request) {
// handleRequest(w, r, ctx, firestoreClient, storageClient)
//}
//http.HandleFunc("/build", h)
//log.Printf("Remap Build Server is running on port %s.\n", port)
//if err := http.ListenAndServe(":"+port, nil); err != nil {
// log.Fatal(err)
//}
}
func createFirebaseApp(ctx context.Context) *firebase.App {
//sa := option.WithCredentialsFile("service-account-remap-b2d08-70b4596e8a05.json")
//app, err := firebase.NewApp(ctx, nil, sa)
app, err := firebase.NewApp(ctx, nil)
if err != nil {
log.Fatalln(err)
}
return app
}
func sendFailureResponseWithError(ctx context.Context, taskId string, client *firestore.Client, w http.ResponseWriter, cause error) {
log.Printf("[ERROR] %s\n", cause.Error())
// Update the task status to "failure".
err := database.UpdateTask(ctx, client, taskId, "failure", "", cause.Error(), "")
if err != nil {
// Ignore the error about updating the task status.
log.Printf("[ERROR] %s\n", err.Error())
}
// Return the error message, but return the status code 200 to avoid the retry with Cloud Tasks.
w.WriteHeader(http.StatusOK)
io.WriteString(w, cause.Error())
}
func sendFailureResponseWithStdoutAndStderr(ctx context.Context, taskId string, client *firestore.Client, w http.ResponseWriter, message string, stdout string, stderr string) {
log.Printf("[ERROR] %s\n", message)
// Update the task status to "failure".
err := database.UpdateTask(ctx, client, taskId, "failure", stdout, stderr, "")
if err != nil {
log.Printf("[ERROR] %s\n", err.Error())
}
// Return the error message, but return the status code 200 to avoid the retry with Cloud Tasks.
w.WriteHeader(http.StatusOK)
io.WriteString(w, message)
}
func sendSuccessResponseWithStdout(ctx context.Context, taskId string, client *firestore.Client, w http.ResponseWriter, stdout string, remoteFirmwareFilePath string) error {
err := database.UpdateTask(ctx, client, taskId, "success", stdout, "", remoteFirmwareFilePath)
if err != nil {
return err
}
w.WriteHeader(http.StatusOK)
io.WriteString(w, "Building succeeded")
return nil
}
// Handles the HTTP request.
func handleRequest(w http.ResponseWriter, r *http.Request, ctx context.Context, firestoreClient *firestore.Client, storageClient *storage.Client) {
log.Printf("%s %s %s\n", r.Method, r.URL, r.Proto)
// Fetch the query parameters (uid and taskId).
params, err := web.ParseQueryParameters(r)
if err != nil {
log.Printf("[ERROR] %s\n", err.Error())
// Return the error message, but return the status code 200 to avoid the retry with Cloud Tasks.
w.WriteHeader(http.StatusOK)
io.WriteString(w, err.Error())
return
}
log.Printf("[INFO] uid: %s, taskId: %s\n", params.Uid, params.TaskId)
// Fetch the task information from the Firestore.
task, err := database.FetchTaskInfo(firestoreClient, params)
if err != nil {
log.Printf("[ERROR] %s\n", err.Error())
// Return the error message, but return the status code 200 to avoid the retry with Cloud Tasks.
w.WriteHeader(http.StatusOK)
io.WriteString(w, err.Error())
return
}
log.Printf("[INFO] The task [%+v] exists\n", params.TaskId)
// Check whether the uid in the task information and passed uid are the same.
if task.Uid != params.Uid {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, fmt.Errorf("uid in the task information and passed uid are not the same"))
return
}
// Check the authentication token.
err = auth.CheckAuthenticationToken(r)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
// Parse the parameters JSON string.
parametersJson, err := parameter.ParseParameterJson(task.ParametersJson)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
// Update the task status to "building".
err = database.UpdateTaskStatusToBuilding(ctx, firestoreClient, params.TaskId)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
// Fetch the firmware information from the Firestore.
firmware, err := database.FetchFirmwareInfo(firestoreClient, task)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
log.Printf("[INFO] The firmware [%+v] exists. The keyboard definition ID is [%+v]\n", task.FirmwareId, firmware.KeyboardDefinitionId)
// Check whether the firmware is enabled.
if !firmware.Enabled {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, fmt.Errorf("the firmware is not enabled"))
return
}
// Fetch the keyboard files from the Firestore.
keyboardFiles, err := database.FetchKeyboardFiles(firestoreClient, task.FirmwareId)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
log.Printf("[INFO] keyboardFiles: %+v\n", keyboardFiles)
// Fetch the keymap files from the Firestore.
keymapFiles, err := database.FetchKeymapFiles(firestoreClient, task.FirmwareId)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
log.Printf("[INFO] keymapFiles: %+v\n", keymapFiles)
// Replace parameters.
keyboardFiles = parameter.ReplaceParameters(keyboardFiles, parametersJson.Keyboard)
keymapFiles = parameter.ReplaceParameters(keymapFiles, parametersJson.Keymap)
// Generate the keyboard ID.
keyboardId := build.GenerateKeyboardId(firmware)
log.Printf("[INFO] keyboardId: %s\n", keyboardId)
// Prepare the keyboard directory.
keyboardDirectoryPath, err := build.PrepareKeyboardDirectory(keyboardId, firmware.QmkFirmwareVersion)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
log.Printf("[INFO] Keyboard directory path: %s\n", keyboardDirectoryPath)
// Delete the keyboard directory after the function returns.
defer func() {
// Delete the keyboard directory.
err = build.DeleteKeyboardDirectory(keyboardId, firmware.QmkFirmwareVersion)
if err != nil {
log.Printf("[ERROR] %s\n", err.Error())
}
log.Printf("[INFO] Deleted the keyboard directory: %s\n", keyboardDirectoryPath)
}()
// Create the keyboard files.
err = build.CreateFirmwareFiles(keyboardDirectoryPath, keyboardFiles)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
// Create the keymap files.
keymapDirectoryPath := filepath.Join(keyboardDirectoryPath, "keymaps", "remap")
err = os.MkdirAll(keymapDirectoryPath, 0755)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
err = build.CreateFirmwareFiles(keymapDirectoryPath, keymapFiles)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
// Build the QMK Firmware.
buildResult := build.BuildQmkFirmware(keyboardId, firmware.QmkFirmwareVersion)
log.Printf("[INFO] buildResult: %v\n", buildResult.Success)
if !buildResult.Success {
sendFailureResponseWithStdoutAndStderr(ctx, params.TaskId, firestoreClient, w, "Building failed", buildResult.Stdout, buildResult.Stderr)
return
}
log.Printf("[INFO] Building succeeded\n")
// Create the local firmware file path.
firmwareFileName, err := parameter.FetchFirmwareFileName(buildResult.Stdout)
if err != nil {
sendFailureResponseWithStdoutAndStderr(ctx, params.TaskId, firestoreClient, w, err.Error(), buildResult.Stdout, buildResult.Stderr)
return
}
localFirmwareFilePath := filepath.Join(
build.QmkFirmwareBaseDirectoryPath+firmware.QmkFirmwareVersion, firmwareFileName)
log.Printf("[INFO] localFirmwareFilePath: %s\n", localFirmwareFilePath)
// Upload the firmware file to the Cloud Storage.
firmwareFileNameWithTimestamp := build.CreateFirmwareFileNameWithTimestamp(firmwareFileName)
remoteFirmwareFilePath, err := database.UploadFirmwareFileToCloudStorage(ctx, storageClient, params.Uid, firmwareFileNameWithTimestamp, localFirmwareFilePath)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
return
}
log.Printf("[INFO] remoteFirmwareFilePath: %s\n", remoteFirmwareFilePath)
// Update the task status to "success".
err = sendSuccessResponseWithStdout(ctx, params.TaskId, firestoreClient, w, buildResult.Stdout, remoteFirmwareFilePath)
if err != nil {
sendFailureResponseWithError(ctx, params.TaskId, firestoreClient, w, err)
}
}