summaryrefslogtreecommitdiffhomepage
path: root/derelict.go
blob: ef0b6c3395452d2de3926d0b17de20db5f77aad9 (plain)
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
package main

import (
	"crypto/sha1"
	"embed"
	"encoding/hex"
	"encoding/json"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"regexp"
	"sort"

	"github.com/gorilla/mux"
)

//go:embed *.json *.css *.js *.svg
var content embed.FS

//go:embed *.tmpl
var internal embed.FS

var (
	templates  *template.Template
	root       string
	validToken *regexp.Regexp
)

func main() {
	initRoot()

	validToken = regexp.MustCompile(`[a-fA-F0-9]+`)

	port := os.Getenv("DERELICTPORT")
	if port == "" {
		port = "8080"
	}

	templates = template.Must(template.ParseFS(internal, "*.tmpl"))

	router := mux.NewRouter()
	router.HandleFunc("/", handleRecent).Methods("GET")
	router.HandleFunc("/view/{id:[_0-9a-f]+}", handleView).Methods("GET")
	router.HandleFunc("/battles", handleBattlesPost).Methods("POST")
	router.HandleFunc("/battles/{id:[_0-9a-f]+}", handleBattlesId).Methods("GET")
	router.PathPrefix("/").Handler(http.FileServer(http.FS(content)))
	log.Fatal(http.ListenAndServe(":"+port, router))
}

func initRoot() {
	root = os.Getenv("DERELICTROOT")
	if root == "" {
		root = ".derelict"
	}
	os.Mkdir(root, 0755)
	os.Mkdir(root+"/battles", 0755)
	os.Mkdir(root+"/tokens", 0700)
}

func handleBattlesPost(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("Derelict-Token")
	if !validToken.MatchString(token) {
		http.Error(w, "Invalid token", http.StatusBadRequest)
		return
	}
	_, err := os.Stat(root + "/tokens/" + token)
	if _, ok := err.(*os.PathError); ok {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}
	if err != nil {
		http.Error(w, "Unexpected error 1", http.StatusInternalServerError)
		return
	}
	var wrecks []Wreck
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Unexpected error 2", http.StatusInternalServerError)
		return
	}
	err = json.Unmarshal(data, &wrecks)
	if err != nil {
		http.Error(w, "Error in body", http.StatusBadRequest)
		return
	}
	hash := sha1.Sum(data)
	name := hex.EncodeToString(hash[:])
	ioutil.WriteFile(root+"/battles/"+name, data, 0644)
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(name))
}

func handleBattlesId(w http.ResponseWriter, r *http.Request) {
	id := mux.Vars(r)["id"]
	w.Header().Add("Content-Type", "application/json")
	http.ServeFile(w, r, root+"/battles/"+id)
}

func handleRecent(w http.ResponseWriter, r *http.Request) {
	files, err := ioutil.ReadDir(root + "/battles")
	if err != nil {
		panic(err)
	}
	sort.Slice(files, func(lhs, rhs int) bool {
		return files[lhs].ModTime().After(files[rhs].ModTime())
	})
	count := 10
	if count > len(files) {
		count = len(files)
	}
	templates.ExecuteTemplate(w, "recent", files[:count])
}

func handleView(w http.ResponseWriter, r *http.Request) {
	id := mux.Vars(r)["id"]
	templates.ExecuteTemplate(w, "view", id)
}