-
Notifications
You must be signed in to change notification settings - Fork 1
/
ws.go
317 lines (292 loc) · 8.17 KB
/
ws.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
/*
WebChunk, web server for block game maps
Copyright (C) 2022 Maxim Zhuchkov
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Contact me via mail: [email protected] or Discord: MaX#6717
*/
package main
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"image"
"image/png"
"log"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/maxsupermanhd/WebChunk/primitives"
"github.com/mitchellh/mapstructure"
)
var (
wsUpgrader = websocket.Upgrader{
HandshakeTimeout: 2 * time.Second,
ReadBufferSize: 0,
WriteBufferSize: 0,
WriteBufferPool: nil,
Subprotocols: nil,
Error: func(_ http.ResponseWriter, r *http.Request, status int, reason error) {
log.Printf("Websocket error from client %v: %v %v", r.RemoteAddr, status, reason.Error())
},
CheckOrigin: func(r *http.Request) bool {
return true
},
EnableCompression: true,
}
wsClients sync.WaitGroup
)
type wsmessage struct {
msgType int
msgData []byte
}
func wsClientHandlerWrapper(exitchan <-chan struct{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
wsClientHandler(w, r, exitchan)
}
}
func wsClientHandler(w http.ResponseWriter, r *http.Request, exitchan <-chan struct{}) {
c, err := wsUpgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Websocket upgrade error: %s", err)
return
}
wsClients.Add(1)
defer wsClients.Done()
defer c.Close()
log.Printf("Websocket %s connected", r.RemoteAddr)
pingTicker := time.NewTicker(2 * time.Second)
e := globalEventRouter.Connect()
defer globalEventRouter.Disconnect(e)
e <- mapEvent{
Action: "updateLayers",
Data: listttypes(),
}
e <- mapEvent{
Action: "updateWorldsAndDims",
Data: listNamesWnD(),
}
eQ := make(chan error, 2)
wQ := make(chan wsmessage, 32)
var wQdidClose atomic.Bool
rQ := make(chan wsmessage, 32)
var wg sync.WaitGroup
wg.Add(2)
go func() {
asyncWriter(c, wQ, eQ)
wg.Done()
}()
go func() {
go asyncReader(c, rQ, eQ)
wg.Done()
}()
subbedTiles := map[primitives.ImageLocation]bool{}
asyncTileRequestor := func(loc primitives.ImageLocation) {
if loc.Dimension == "" || loc.World == "" {
return
}
img, err := imageGetSync(loc, false)
if err != nil {
b, _ := json.Marshal(map[string]any{
"Action": "message",
"Data": fmt.Sprintf("Error rendering tile %s: %s", loc.String(), err),
})
wQ <- wsmessage{
msgType: websocket.TextMessage,
msgData: b,
}
return
}
// TODO: fix time of check time of use
ret := marshalBinaryTileUpdate(loc, img)
if !wQdidClose.Load() {
wQ <- wsmessage{
msgType: websocket.BinaryMessage,
msgData: ret,
}
}
}
clientLoop:
for {
select {
case t := <-pingTicker.C:
wQ <- wsmessage{
msgType: websocket.PingMessage,
msgData: []byte(fmt.Sprint(t.Unix())),
}
case m := <-e:
log.Printf("Websocket %s relaying message %#+v", r.RemoteAddr, m.Action)
b, err := json.Marshal(m)
if err != nil {
log.Printf("Failed to marshal progress: %v\n", err)
break clientLoop
}
wQ <- wsmessage{
msgType: websocket.TextMessage,
msgData: b,
}
case err := <-eQ:
wQdidClose.Store(true)
close(wQ)
c.Close()
if err == nil {
log.Printf("Websocket %s disconnected with nil err", r.RemoteAddr)
break clientLoop
} else {
if websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway, websocket.CloseMessage) {
log.Printf("Websocket %s error: %s", r.RemoteAddr, err)
} else {
log.Printf("Websocket %s disconnected", r.RemoteAddr)
}
}
break clientLoop
case <-exitchan:
log.Printf("Shutting down websocket %s", r.RemoteAddr)
wQ <- wsmessage{
msgType: websocket.TextMessage,
msgData: []byte(`{"Action": "message", "Data": "Disconnecting because WebChunk server is shutting down"}`),
}
wQ <- wsmessage{
msgType: websocket.CloseMessage,
msgData: []byte{},
}
break clientLoop
case m := <-rQ:
if m.msgType == websocket.TextMessage {
var msg mapEvent
err := json.Unmarshal(m.msgData, &msg)
if err != nil {
log.Printf("Failed to decode websocket client %s message: %s", r.RemoteAddr, err.Error())
}
switch msg.Action {
case "tileSubscribe":
var loc primitives.ImageLocation
err := mapstructure.Decode(msg.Data, &loc)
if err != nil {
log.Printf("Websocket %s sent malformed tile sub: %s", r.RemoteAddr, err.Error())
break
}
_, ok := subbedTiles[loc]
if ok {
log.Printf("Websocket %s tileSub already subbed %s", r.RemoteAddr, loc)
} else {
subbedTiles[loc] = true
log.Printf("Websocket %s tileSub %s", r.RemoteAddr, loc)
}
go asyncTileRequestor(loc)
case "tileUnsubscribe":
var loc primitives.ImageLocation
err := mapstructure.Decode(msg.Data, &loc)
if err != nil {
log.Printf("Websocket %s sent malformed tile unsub: %s", r.RemoteAddr, err.Error())
break
}
_, ok := subbedTiles[loc]
if ok {
delete(subbedTiles, loc)
log.Printf("Websocket %s tileUnsub %s", r.RemoteAddr, loc)
} else {
log.Printf("Websocket %s tileUnsub does not exist %s", r.RemoteAddr, loc)
}
case "resubWorldDimension":
data, ok := msg.Data.(map[string]any)
if !ok {
log.Printf("Websocket %s sent malformed tile unsub: data not map", r.RemoteAddr)
break
}
nWorld, ok := data["World"].(string)
if !ok {
log.Printf("Websocket %s sent malformed tile unsub: failed to read World name", r.RemoteAddr)
break
}
nDimension, ok := data["Dimension"].(string)
if !ok {
log.Printf("Websocket %s sent malformed tile unsub: failed to read Dimension name", r.RemoteAddr)
break
}
oldSubbed := subbedTiles
subbedTiles = map[primitives.ImageLocation]bool{}
for k := range oldSubbed {
k.World = nWorld
k.Dimension = nDimension
subbedTiles[k] = true
go asyncTileRequestor(k)
}
default:
log.Printf("Websocket %s wrong action %#+v", r.RemoteAddr, msg.Action)
}
} else {
log.Printf("Websocket %s message %d len %d", r.RemoteAddr, m.msgType, len(m.msgData))
}
}
}
log.Printf("Websocket %s loop exited", r.RemoteAddr)
wg.Wait()
log.Printf("Websocket handler %s exited", r.RemoteAddr)
}
var (
pngEncoder = &png.Encoder{
CompressionLevel: png.NoCompression,
}
)
func marshalBinaryTileUpdate(loc primitives.ImageLocation, img *image.RGBA) []byte {
buf := bytes.NewBuffer([]byte{})
binary.Write(buf, binary.BigEndian, uint8(0x01))
binary.Write(buf, binary.BigEndian, uint32(len(loc.World)))
buf.WriteString(loc.World)
binary.Write(buf, binary.BigEndian, uint32(len(loc.Dimension)))
buf.WriteString(loc.Dimension)
binary.Write(buf, binary.BigEndian, uint32(len(loc.Variant)))
buf.WriteString(loc.Variant)
binary.Write(buf, binary.BigEndian, uint8(loc.S))
binary.Write(buf, binary.BigEndian, int32(loc.X))
binary.Write(buf, binary.BigEndian, int32(loc.Z))
if img != nil {
pngEncoder.Encode(buf, img)
}
return buf.Bytes()
}
func asyncWriter(c *websocket.Conn, q chan wsmessage, e chan error) {
for m := range q {
err := c.WriteMessage(m.msgType, m.msgData)
if err != nil {
e <- err
return
}
if m.msgType == websocket.CloseMessage {
c.Close()
return
}
}
}
func asyncReader(c *websocket.Conn, q chan wsmessage, e chan error) {
for {
msgt, msgd, err := c.ReadMessage()
if err != nil {
e <- err
return
}
if msgt == websocket.PongMessage || msgt == websocket.PingMessage {
continue
}
if msgt == websocket.CloseMessage {
e <- nil
return
}
q <- wsmessage{
msgType: msgt,
msgData: msgd,
}
}
}