-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
206 lines (170 loc) · 4.7 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
package main
import (
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"zombiezen.com/go/capnproto2"
"github.com/gorilla/securecookie"
)
var (
addr = flag.String("addr", ":8000", "HTTP server address")
apiAddr = flag.String("api_addr", ":8001", "RPC server address")
templates = tmpl{template.Must(template.ParseGlob("templates/*.html"))}
db datastore
secretz string
s *securecookie.SecureCookie
globalAIEndpoint *aiEndpoint
)
const (
clientId = "07ef388cb32ffbbd5146"
)
func main() {
flag.Parse()
var err error
if db, err = initDB("gobots.db"); err != nil {
log.Fatal("Couldn't open the database, SHUT IT DOWN")
}
if secretz, err = initSecretz(); err != nil {
log.Fatal("Ain't got no GitHub client secret!!")
}
if s, err = initKeys(); err != nil {
log.Fatal("Can't encrypt the cookies! WHATEVER WILL WE DO")
}
http.HandleFunc("/", withLogin(serveIndex))
http.HandleFunc("/game/", withLogin(serveGame))
http.HandleFunc("/gameWire/", withLogin(serveGameWire))
http.HandleFunc("/auth", withLogin(serveAuth))
http.HandleFunc("/loadBots", withLogin(loadBots))
http.HandleFunc("/startMatch", withLogin(startMatch))
http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("js"))))
http.Handle("/img/", http.StripPrefix("/img/", http.FileServer(http.Dir("img"))))
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
globalAIEndpoint, err = startAIEndpoint(*apiAddr, db)
if err != nil {
log.Fatal("AI RPC endpoint failed to start:", err)
}
err = http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("Yeah...so about that whole server thing: ", err)
}
}
func serveIndex(c context) {
data := tmplData{
Data: map[string]interface{}{
"Bots": globalAIEndpoint.listOnlineAIs(),
},
Scripts: []template.URL{
"/js/main.js",
},
}
if err := templates.ExecuteTemplate(c, "index.html", data); err != nil {
serveError(c.w, err)
}
}
func serveGame(c context) {
replay, err := db.lookupGame(c.gameID())
d := capnp.ToData(replay)
data := tmplData{
Data: map[string]interface{}{
"Replay": replay,
"GameID": c.gameID(),
"Exists": err != errDatastoreNotFound,
"ReplayString": string(d),
},
}
if err := templates.ExecuteTemplate(c, "game.html", data); err != nil {
serveError(c.w, err)
}
}
func serveGameWire(c context) {
replay, _ := db.lookupGame(c.gameID())
d := capnp.ToData(replay)
c.w.Write(d)
}
func serveError(w http.ResponseWriter, err error) {
w.Write([]byte("Internal Server Error"))
log.Printf("Error: %v\n", err)
}
func startMatch(c context) {
//ai1, ai2 := c.r.PostFormValue("ai1"), c.r.PostFormValue("ai2")
//TODO DOIAFJHJKSHLAJSDLKJASLKDJ
http.Redirect(c.w, c.r, "/game/GAMEIDHERE", http.StatusFound)
}
func loadBots(c context) {
uid := userID(c.p.Name)
_, token, err := db.createAI(uid, &aiInfo{Nick: c.r.PostFormValue("nick")})
if err != nil {
serveError(c.w, err)
return
}
fmt.Fprintln(c.w, "Congrats, your token is:", token)
}
func serveAuth(c context) {
if c.r.FormValue("state") != c.magicToken {
log.Println("They're spoofing GitHub's API. I AM THE ONE WHO KNOCKS (on GitHub's API server)")
return
}
resp, err := http.PostForm("https://github.com/login/oauth/access_token", url.Values{
"client_id": {clientId},
"client_secret": {secretz},
"code": {c.r.FormValue("code")},
})
if err != nil {
log.Println(err)
return
}
defer resp.Body.Close()
d, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
return
}
sRep := string(d)
// http://i.imgur.com/c4jt321.png
is, ie := strings.Index(sRep, "=")+1, strings.Index(sRep, "&")
accessToken := sRep[is:ie]
nutFact, err := loadCookie(c.r)
if err != nil {
log.Println(err)
// This is weird, they must have cookies off, which makes it hard for us to
// validate them. Screw 'em for now
return
}
// Set their access token to what we just got, and create a user with that token
if nutFact.AccessToken == "" {
nutFact.AccessToken = accessToken
go db.createUser(userID(accessToken))
}
if encoded, err := s.Encode("info", nutFact); err == nil {
cookie := &http.Cookie{
Name: "info",
Value: encoded,
Path: "/",
}
http.SetCookie(c.w, cookie)
}
http.Redirect(c.w, c.r, "/", http.StatusFound)
}
func username(uID userID) string {
resp, err := http.Get("https://api.github.com/user?access_token=" + string(uID))
if err != nil {
return ""
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ""
}
var data map[string]interface{}
if err := json.Unmarshal(b, &data); err != nil {
log.Println(err)
return ""
}
return data["login"].(string)
}