forked from Dri0m/9o3o
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
287 lines (239 loc) · 7.2 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
280
281
282
283
284
285
286
287
package main
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
_ "github.com/mattn/go-sqlite3"
"golang.org/x/exp/slices"
)
type Config struct {
FPDatabase string `json:"fpDatabase"`
VotesDatabase string `json:"votesDatabase"`
FileExtensions []string `json:"fileExtensions"`
FilteredTags []string `json:"filteredTags"`
}
type Entry struct {
UUID string `json:"uuid"`
Title string `json:"title"`
LaunchCommand string `json:"launchCommand"`
Zipped bool `json:"zipped"`
Extreme bool `json:"extreme"`
VotesWorking int `json:"votesWorking"`
VotesBroken int `json:"votesBroken"`
}
var (
config Config
fpDatabase *sql.DB
votesDatabase *sql.DB
)
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMicro
zerolog.SetGlobalLevel(zerolog.DebugLevel)
// Load config.json
configFile, err := os.ReadFile("config.json")
if err != nil {
log.Fatal().Err(err).Msg("failed to read config.json")
} else if err := json.Unmarshal([]byte(configFile), &config); err != nil {
log.Fatal().Err(err).Msg("failed to parse config.json")
} else {
log.Debug().Msg("loaded config.json")
}
// Connect to Flashpoint database
fpDatabase, err = sql.Open("sqlite3", config.FPDatabase)
if err != nil {
log.Fatal().Err(err).Msg("failed to open Flashpoint database")
}
defer fpDatabase.Close()
log.Debug().Msg("connected to Flashpoint database")
// Create votes database if it doesn't exist
if _, err := os.Stat(config.VotesDatabase); errors.Is(err, os.ErrNotExist) {
if _, err := os.Create(config.VotesDatabase); err != nil {
log.Fatal().Err(err).Msg("failed to initialize votes database")
}
log.Debug().Msg("created votes database")
}
// Connect to votes database
votesDatabase, err = sql.Open("sqlite3", config.VotesDatabase+"?cache=shared&mode=rwc")
if err != nil {
log.Fatal().Err(err).Msg("failed to open votes database")
}
votesDatabase.SetMaxOpenConns(1)
defer votesDatabase.Close()
log.Info().Msg("connected to votes database")
// Create vote table if it doesn't exist
_, err = votesDatabase.Exec(`
CREATE TABLE IF NOT EXISTS votes (
id VARCHAR(36) PRIMARY KEY,
working INTEGER,
broken INTEGER
)
`)
if err != nil {
log.Fatal().Err(err).Msg("failed to initialize votes table")
}
// Set up and start server
http.HandleFunc("/get", getHandler)
http.HandleFunc("/working", votesHandler)
http.HandleFunc("/broken", votesHandler)
server := &http.Server{
Addr: "127.0.0.1:8985",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Info().Str("addr", server.Addr).Msg("server started")
err = server.ListenAndServe()
if err != nil {
log.Err(err).Msg("server error")
}
}
// Return JSON-formatted info about a specific or random entry
func getHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
uuid := query.Get("id")
var entry *Entry
for {
var err error
if entry, err = getEntry(uuid); err != nil {
var response string
if err == sql.ErrNoRows {
response = "the specified UUID is invalid"
} else {
response = "failed to obtain entry from database"
}
log.Error().Err(err).Str("uuid", uuid).Msg(response)
w.WriteHeader(http.StatusInternalServerError)
writeMessage(w, response)
return
}
if entry.Extreme && len(uuid) == 0 && strings.ToLower(query.Get("filter")) == "true" {
continue
}
break
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(entry); err != nil {
log.Error().Err(err).Msg("failed to marshal response to the user")
writeServerError(w)
return
}
log.Debug().Msgf("served %v", r.URL.RequestURI())
}
// Add new vote for the specified entry
func votesHandler(w http.ResponseWriter, r *http.Request) {
var response string
if err := addVote(r.URL.Query().Get("id"), r.URL.Path == "/working"); err != nil {
log.Error().Err(err).Msg("failed to add vote")
if err == sql.ErrNoRows {
response = "the specified UUID is invalid"
} else {
response = "internal server error"
w.WriteHeader(http.StatusInternalServerError)
}
} else {
response = "success"
}
writeMessage(w, response)
log.Debug().Msgf("received %v (%v)", r.URL.RequestURI(), response)
}
// Make sure entry has a valid UUID and contains a supported file extension in the launch command
func getEntry(uuid string) (*Entry, error) {
if len(uuid) != 0 && !verifyUUID(uuid) {
return nil, sql.ErrNoRows
}
var suffix string
if len(uuid) == 0 {
suffix = "ORDER BY random() LIMIT 1"
} else {
suffix = "AND id = ?"
}
var entry Entry
var tagsStr string
fpRow := fpDatabase.QueryRow(fmt.Sprintf(`
SELECT * FROM (
SELECT game.id, game.title, game.tagsStr,
CASE WHEN activeDataId ISNULL THEN 0 ELSE 1 END AS activeDataOnDisk,
coalesce(game_data.launchCommand, game.launchCommand) AS launchCommand
FROM game LEFT JOIN game_data ON game.id = game_data.gameId
) WHERE (launchCommand LIKE "%%.%s") %s
`, strings.Join(config.FileExtensions, `" OR launchCommand LIKE "%.`), suffix), uuid)
if err := fpRow.Scan(&entry.UUID, &entry.Title, &tagsStr, &entry.Zipped, &entry.LaunchCommand); err != nil {
return nil, err
}
entry.Extreme = false
for _, tag := range strings.Split(tagsStr, "; ") {
if slices.Contains(config.FilteredTags, tag) {
entry.Extreme = true
break
}
}
votesRow := votesDatabase.QueryRow("SELECT working, broken FROM votes WHERE id = ?", uuid)
if err := votesRow.Scan(&entry.VotesWorking, &entry.VotesBroken); err != sql.ErrNoRows && err != nil {
return nil, err
}
return &entry, nil
}
// Update votes database with new vote
func addVote(uuid string, working bool) error {
if !verifyUUID(uuid) {
return sql.ErrNoRows
}
row := fpDatabase.QueryRow(fmt.Sprintf(`
SELECT * FROM (
SELECT game.id, coalesce(game_data.launchCommand, game.launchCommand) AS launchCommand
FROM game LEFT JOIN game_data ON game.id = game_data.gameId
) WHERE (launchCommand LIKE "%%.%s") AND id = ?
`, strings.Join(config.FileExtensions, `" OR launchCommand LIKE "%.`)), uuid)
if err := row.Err(); err != nil {
return err
}
var (
workingInt int
brokenInt int
voteString string
)
if working {
workingInt = 1
brokenInt = 0
voteString = "working"
} else {
workingInt = 0
brokenInt = 1
voteString = "broken"
}
if _, err := votesDatabase.Exec(fmt.Sprintf(`
INSERT INTO votes (id, working, broken) VALUES (?, %[1]d, %[2]d)
ON CONFLICT (id) DO UPDATE SET %[3]s = %[3]s + 1
`, workingInt, brokenInt, voteString), uuid); err != nil {
return err
}
return nil
}
// Check if UUID is the correct format
func verifyUUID(uuid string) bool {
if len(uuid) != 36 {
return false
}
for _, v := range uuid {
if !strings.Contains("abcdefghijklmnopqrstuvwxyz0123456789-", string(v)) {
return false
}
}
return true
}
func writeServerError(w http.ResponseWriter) {
w.WriteHeader(http.StatusInternalServerError)
writeMessage(w, "internal server error")
}
func writeMessage(w http.ResponseWriter, message string) {
if _, err := w.Write([]byte(message)); err != nil {
log.Error().Err(err).Msg("failed write response to the user")
return
}
}