summaryrefslogtreecommitdiffhomepage
path: root/storage.go
blob: 9172e96c1ebddd0c11a896d4451f8e637d8a51b7 (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
package main

import (
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"sort"
	"strconv"
)

type Storage struct {
	Path string
}

var (
	tokenPattern = regexp.MustCompile(`[a-fA-F0-9]{10,}`)
)

func (s *Storage) MustInit() error {
	os.Mkdir(s.Path, 0755)
	os.Mkdir(s.Path+"/battles", 0755)
	os.Mkdir(s.Path+"/tokens", 0700)
	return nil
}

func (s *Storage) CanPost(token string) (bool, error) {
	if !tokenPattern.MatchString(token) {
		return false, errors.New("invalid token")
	}
	_, err := os.Stat(s.Path + "/tokens/" + token)
	return err == nil, nil
}

func (b *Battle) CalculateHash() {
	hash := sha1.New()
	killmails := b.Killmails
	sort.Slice(killmails, func(lhs, rhs int) bool {
		return killmails[lhs].Id < killmails[rhs].Id
	})
	for _, km := range killmails {
		io.WriteString(hash, strconv.FormatUint(km.Id, 10))
	}
	sum := hash.Sum(nil)
	b.Id = hex.EncodeToString(sum[:])
}

func (s *Storage) AddBattle(battle *Battle) error {
	if len(battle.Killmails) < 1 {
		return errors.New("missing killmails")
	}
	battle.CalculateHash()
	data, err := json.Marshal(battle)
	if err != nil {
		return err
	}

	return ioutil.WriteFile(s.Path+"/battles/"+battle.Id, data, 0644)
}

func (s *Storage) ServeBattle(id string, w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content-Type", "application/json")
	http.ServeFile(w, r, s.Path+"/battles/"+id)
}

func (s *Storage) ListRecentBattles(count int) ([]Battle, error) {
	files, err := ioutil.ReadDir(s.Path + "/battles")
	if err != nil {
		return nil, err
	}

	sort.Slice(files, func(lhs, rhs int) bool {
		return files[lhs].ModTime().After(files[rhs].ModTime())
	})

	battles := make([]Battle, 0, count)

	for i := 0; i < count && i < len(files); i++ {
		battles = append(battles, Battle{Id: files[i].Name(), LastModified: files[i].ModTime()})
	}

	return battles, nil
}