forked from sparkoo/csgo-2d-demo-viewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
184 lines (162 loc) · 4.51 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
package main
import (
"compress/gzip"
"csgo-2d-demo-player/conf"
"csgo-2d-demo-player/pkg/faceit"
"csgo-2d-demo-player/pkg/message"
"csgo-2d-demo-player/pkg/parser"
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs"
"google.golang.org/protobuf/proto"
"html/template"
"io"
"log"
"net/http"
)
var config *conf.Conf
func main() {
config = conf.ParseArgs()
server()
}
func handleMessages(in chan []byte, out chan []byte) {
for msg := range in {
var messageObj message.Message
err := json.Unmarshal(msg, &messageObj)
if err != nil {
log.Print("failed unmarshal websocket message", err)
}
switch messageObj.MsgType {
case message.Message_PlayRequestType:
go playDemo(out, messageObj.Demo.MatchId)
}
}
}
func server() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
temp, err := template.ParseFiles("templates/list.html")
if err != nil {
http.Error(writer, err.Error(), 500)
}
if temp.Execute(writer, nil) != nil {
http.Error(writer, err.Error(), 500)
}
})
//mux.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) {
// temp, err := template.ParseFiles("templates/test.html")
// if err != nil {
// http.Error(writer, err.Error(), 500)
// }
//
// if temp.Execute(writer, nil) != nil {
// http.Error(writer, err.Error(), 500)
// }
//})
playerFileServer := http.FileServer(http.Dir("web/player/build"))
mux.Handle("/player/",
http.StripPrefix("/player", playerFileServer))
assetsFileServer := http.FileServer(http.Dir("./assets"))
mux.Handle("/assets/", http.StripPrefix("/assets", assetsFileServer))
mux.HandleFunc("/ws", func(writer http.ResponseWriter, request *http.Request) {
// Upgrade our raw HTTP connection to a websocket based one
upgrader := websocket.Upgrader{}
if request.Host == "localhost:8080" {
upgrader.CheckOrigin = func(r *http.Request) bool {
return true
}
}
conn, err := upgrader.Upgrade(writer, request, nil)
if err != nil {
log.Print("Error during connection upgradation:", err)
return
}
out := make(chan []byte)
in := make(chan []byte)
go handleMessages(in, out)
// out routine
go func() {
defer func() {
if closeErr := conn.Close(); closeErr != nil {
log.Printf("failed to close connection [out] '%s'", closeErr.Error())
}
}()
for msg := range out {
err = conn.WriteMessage(websocket.BinaryMessage, msg)
if err != nil {
log.Println("Error during message writing:", err)
break
}
}
}()
// in routine
go func() {
defer func() {
if closeErr := conn.Close(); closeErr != nil {
log.Printf("failed to close connection [in] '%s'", closeErr.Error())
}
}()
for {
_, msg, err := conn.ReadMessage()
if err != nil {
log.Println("Error during message reading:", err)
break
}
in <- msg
}
}()
})
log.Println("Listening on ", config.Port, " ...")
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.Port), mux))
}
func playDemo(out chan []byte, matchId string) {
if matchId == "" {
sendError("no matchId", out)
return
}
demoFile, closers, err := obtainDemoFile(matchId)
if err != nil {
sendError(err.Error(), out)
return
}
defer func() {
for _, c := range closers {
if closeErr := c.Close(); closeErr != nil {
log.Printf("[%s] failed to close resource. %s", matchId, closeErr)
}
}
}()
err = parser.Parse(demoFile, func(msg *message.Message, tick demoinfocs.GameState) {
sendMessage(msg, out)
})
if err != nil {
sendError(err.Error(), out)
}
}
func sendMessage(msg *message.Message, out chan []byte) {
payload, protoErr := proto.Marshal(msg)
if protoErr != nil {
sendError(protoErr.Error(), out)
}
out <- payload
}
func sendError(errorMessage string, out chan []byte) {
log.Printf("sending error to client: '%s'", errorMessage)
out <- []byte(fmt.Sprintf("{\"msgType\": %d, \"error\": {\"message\": \"%s\"}}", message.Message_ErrorType, errorMessage))
}
func obtainDemoFile(matchId string) (io.Reader, []io.Closer, error) {
closers := make([]io.Closer, 0)
demoFileReader, streamErr := faceit.DemoStream(matchId)
if streamErr != nil {
return nil, closers, streamErr
}
closers = append(closers, demoFileReader)
gzipReader, gzipErr := gzip.NewReader(demoFileReader)
if gzipErr != nil {
log.Printf("[%s] Failed to create gzip reader from demo. %s", matchId, gzipErr)
return nil, closers, gzipErr
}
closers = append(closers, gzipReader)
return gzipReader, closers, gzipErr
}