-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·448 lines (343 loc) · 10.1 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/*
SURVIVOR SCHEDULER
Josh Spicer <https://joshspicer.com/>
2019 March 23
*/
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"html/template"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"strconv"
"strings"
"time"
)
type DailyAvailability struct {
Halfhours [16]bool // From 4:30pm-12:00pm in half hour increments
}
type Availability struct {
Days [7]DailyAvailability // 0 == Sunday, 6 == Saturday
}
/*
Defines a .survive file datatype.
*/
type SurviveFile struct {
Player string
Availability Availability
CreatedAt time.Time
}
type JSONResponse struct {
Player string
I1 int
I2 int
}
// ========= ENVIRONMENT VARIABLES ==========
//const ENV_ROOT = "/Users/joshspicer/go/src/github.com/joshspicer/survivor-scheduler"
const ENV_ROOT = "/Users/jspicer/go/src/survivor-scheduler-golang"
// ==== STATE ====
var PLAYERS []string
func (ss *SurviveFile) save() error {
// Define the filename with our filesystem naming convention based on struct fields.
filename := fmt.Sprintf("%s/%s.survive", ENV_ROOT, ss.Player)
// Open the file it is exists, or make a new one.
// Either way, mark file as APPENDABLE
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
log.Fatal("Error opening file.", err)
return err
}
// Format data.
avail, err := ss.Availability.availabilityToString()
if err != nil {
return err
}
stringToWrite := fmt.Sprintf("%s%s", avail, "\n")
// Write string to open file.
_, err = f.WriteString(stringToWrite)
if err != nil {
log.Fatal("Error writing to file.", err)
return err
}
// Close the file
err = f.Close()
if err != nil {
log.Fatal("Error closing open file in save()")
return err
}
return nil
}
/**
HELPER:
Given an Availability and a "target" hour on a "target" day, flips the bit.
Mutates the given Availability as it exists in memory
*/
func (aa *Availability) flipAvailabilityBit(dayIdx int, hourIdx int) {
currValue := aa.Days[dayIdx].Halfhours[hourIdx]
day := &aa.Days[dayIdx]
day.Halfhours[hourIdx] = !currValue
}
/**
Appends to (or creates new) .survive file based on given parameters.
Used to update data file on disk with availability changes.
*/
func updateActor(player string, dayIdx int, hourIdx int) (*SurviveFile, error) {
// Load this player's file based on the information given.
sFile, err := loadFile(player)
if err != nil {
log.Print("Error loading file")
return nil, err
}
// Edit player's availability with the given instructions
sFile.Availability.flipAvailabilityBit(dayIdx, hourIdx)
// Save the edits
err = sFile.save()
if err != nil {
log.Print("Error saving file", err)
return nil, err
}
return sFile, nil
}
// Outputs a given Availability as a string.
// Of form:
// 0000:0000:<...7 hex groups...>:0000
func (aa Availability) availabilityToString() (string, error) {
var sb strings.Builder
for idx, day := range aa.Days {
// For each day
str, err := day.dailyAvailabilityToString()
if err != nil {
log.Print("Error converting day availability to string in availabilityToString.")
return "", err
}
// No error, write to master string.
sb.WriteString(str)
// Add a colon if not last day of week.
if idx != 6 {
sb.WriteString(":")
}
}
return sb.String(), nil
}
func (dd DailyAvailability) dailyAvailabilityToString() (string, error) {
// Input: a [16]bool
// Output: 4-character hex string. e.g: 4fcb
const BASE = 16
const DIFF = BASE - 1
var count int64 = 0
for idx, halfhour := range dd.Halfhours {
//0000 0000 0000 0000
if halfhour {
count += int64(math.Pow(float64(2), float64(DIFF-idx)))
}
}
// Convert the count (a base-10 number) into base-16
base16 := strconv.FormatInt(count, 16)
return base16, nil
}
// Convert the hex-encoded availability string into an Availability
func stringToAvailability(availStr string) (*Availability, error) {
// Input eg: 0:c000:0:13:0888:4560:15a0
// where a segment: 0000 <-> FFFF (hex-encoded 16-bit number)
// [1] Split into array with all 7 pieces
arr := strings.Split(availStr, ":")
if len(arr) != 7 {
log.Print("Expect 7 parts of an availability string, got ", len(arr))
return &Availability{}, errors.New("expected 7 parts")
}
AA := Availability{}
// [2] For each chunk (Sunday => Saturday)
for idx, hexNumStr := range arr {
day := &AA.Days[idx]
// [3] Parse hex number into integer
num, err := strconv.ParseInt(hexNumStr, 16, 32)
if err != nil {
log.Print("Unable to parse out the hexNumStr")
return &Availability{}, err
}
// [5] Iterate through string and flip bool of DailyAvail.
for i := 0; i < 16; i++ {
// ANDs the hex value and the bit in question.
if num&(1<<uint(16-i-1)) > 0 {
day.Halfhours[i] = true
}
}
}
return &AA, nil
}
func initFile(player string) (*SurviveFile, error) {
// Init player with zero'd out (free) availability
tmp := &SurviveFile{Player: player, Availability: Availability{}, CreatedAt: time.Now()}
err := tmp.save()
if err != nil {
log.Fatal("Error initializing file", err)
return nil, err
}
return tmp, nil
}
func loadFile(player string) (*SurviveFile, error) {
// Compute file name based off convention
filename := fmt.Sprintf("%s/%s.survive", ENV_ROOT, player)
// Read file from file system.
body, err := ioutil.ReadFile(filename)
// Catch error reading file.
if err != nil {
//log.Fatal("Error loading page!!")
return nil, err
}
// Grab the latest file update
split := strings.Split(string(body), "\n")
// Per convention: every entry end in a newline, so go two lines up to get last entry.
avail := split[len(split)-2]
availability, err := stringToAvailability(avail)
if err != nil {
return nil, err
}
return &SurviveFile{Player: player, Availability: *availability}, nil
}
func playerEditHandler(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path[len("/edit/"):]
player := strings.Split(path, "/")
if len(player) != 1 {
log.Print("Could not parse view input correctly.")
http.NotFound(w, r)
return
}
p, err := loadFile(player[0])
if err != nil {
log.Print("Could not load page player edit handler")
http.NotFound(w, r)
return
}
// Map functions from golang to be reflected in HTML
funcMap := template.FuncMap{
"tableflip": func() string { return "(╯°□°)╯︵ ┻━┻" },
"updateActor": updateActor,
}
tpl := template.Must(template.New("main").Funcs(funcMap).ParseGlob("templates/*.html"))
err = tpl.ExecuteTemplate(w, "playerEdit.html", p)
if err != nil {
log.Fatal(err)
}
}
func updateHandler(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var t JSONResponse
err := decoder.Decode(&t)
if err != nil {
log.Print("Error parsing POST: ", err)
return
}
_, err = updateActor(t.Player, t.I1, t.I2)
if err != nil {
log.Print("Error in the updateHandler, from updateActor: ", err)
}
}
func manageHandler(w http.ResponseWriter, r *http.Request) {
aggregatedWeeklyAvails, err := aggregatedWeeklyAvails(); if err != nil {
log.Print(err)
}
// Map functions from golang to be reflected in HTML
funcMap := template.FuncMap{
"tableflip": func() string { return "(╯°□°)╯︵ ┻━┻" },
}
tpl := template.Must(template.New("main").Funcs(funcMap).ParseGlob("templates/*.html"))
err = tpl.ExecuteTemplate(w, "manage.html", aggregatedWeeklyAvails)
if err != nil {
log.Fatal(err)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
// Map functions from golang to be reflected in HTML
funcMap := template.FuncMap{
"tableflip": func() string { return "(╯°□°)╯︵ ┻━┻" },
}
tpl := template.Must(template.New("main").Funcs(funcMap).ParseGlob("templates/*.html"))
err := tpl.ExecuteTemplate(w, "index.html", PLAYERS)
if err != nil {
log.Fatal(err)
}
}
func errorHandler(w http.ResponseWriter, r *http.Request) {
tpl := template.Must(template.New("main").ParseGlob("templates/*.html"))
err := tpl.ExecuteTemplate(w, "error.html", nil)
if err != nil {
log.Fatal(err)
}
}
// Utilizes conf.survive to flatten all player's availabilities
// into one "master availablity".
// If any one person is unavailable, time slot is marked as "busy", else kept "free"
func aggregatedWeeklyAvails() (Availability, error) {
// "Master" availability
var master Availability
// For each Player, get their availability. Flip master if conflict
for _, player := range PLAYERS {
file, err := loadFile(player); if err != nil {
return Availability{}, err
}
for dayIdx, day := range file.Availability.Days {
for hrIdx := 0; hrIdx < 16; hrIdx++ {
if day.Halfhours[hrIdx] {
master.Days[dayIdx].Halfhours[hrIdx] = true
}
}
}
}
return master, nil
}
/**
*/
func bigBang() error {
newGame, err := os.OpenFile("conf", os.O_RDONLY, 0600)
// If there is no new init file, lets see if we have an existing game to restore from!!
if err != nil {
existingGame, err := os.OpenFile("conf.processed", os.O_RDONLY, 0600); if err != nil {
log.Print("Lack of either new OR existing conf file...")
return err
}
scanner := bufio.NewScanner(existingGame)
for scanner.Scan() {
PLAYERS = append(PLAYERS, scanner.Text())
}
// Existing game restored. Now Return from function with no error.
return nil
}
// === If game has NEVER been initialized we continue down here. ====
scanner := bufio.NewScanner(newGame)
for scanner.Scan() {
PLAYERS = append(PLAYERS, scanner.Text())
_, err := initFile(scanner.Text())
if err != nil {
log.Print("Error init of player. Check config format.")
return err
}
}
err = os.Rename("conf", "conf.processed")
return err
}
/*
Main function. Entry point of program.
*/
func main() {
// If conf.survive exists, initialize game.
err := bigBang()
if err != nil {
log.Print("Error in bigbang", err)
http.HandleFunc("/", errorHandler)
} else {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/edit/", playerEditHandler) // .../view/{week}/{player_name}
http.HandleFunc("/manage/", manageHandler) // .../manage/{week}/
http.HandleFunc("/update", updateHandler) // POST to /update with {week, player,i1,i2}
}
fmt.Print(PLAYERS)
//http.HandleFunc("/save/", saveHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}