-
-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathhandlers.go
484 lines (412 loc) · 11.3 KB
/
handlers.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package main
import (
"encoding/json"
"errors"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"github.com/zorchenhimer/MovieNight/common"
"github.com/gorilla/websocket"
"github.com/nareix/joy4/av/avutil"
"github.com/nareix/joy4/av/pubsub"
"github.com/nareix/joy4/format/flv"
"github.com/nareix/joy4/format/rtmp"
)
var (
//global variable for handling all chat traffic
chat *ChatRoom
// Read/Write mutex for rtmp stream
l = &sync.RWMutex{}
// Map of active streams
channels = map[string]*Channel{}
)
type Channel struct {
que *pubsub.Queue
}
type writeFlusher struct {
httpflusher http.Flusher
io.Writer
}
func (w writeFlusher) Flush() error {
w.httpflusher.Flush()
return nil
}
func wsEmotes(w http.ResponseWriter, r *http.Request) {
file := strings.TrimPrefix(r.URL.Path, "/")
emoteDirSuffix := filepath.Base(emotesDir)
if emoteDirSuffix == filepath.SplitList(file)[0] {
file = strings.TrimPrefix(file, emoteDirSuffix+"/")
}
var body []byte
err := filepath.WalkDir(emotesDir, func(path string, d fs.DirEntry, err error) error {
if d.IsDir() || err != nil || len(body) > 0 {
return nil
}
if filepath.Base(path) != filepath.Base(file) {
return nil
}
body, err = os.ReadFile(path)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
})
if err != nil {
common.LogErrorf("Emote could not be read %s: %v\n", file, err)
w.WriteHeader(http.StatusNotFound)
return
}
if len(body) == 0 {
common.LogErrorf("Found emote file but pulled no data: %v\n", err)
w.WriteHeader(http.StatusNotFound)
return
}
_, err = w.Write(body)
if err != nil {
common.LogErrorf("Could not write emote %s to response: %v\n", file, err)
w.WriteHeader(http.StatusNotFound)
}
}
// Handling the websocket
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true }, //not checking origin
}
// this is also the handler for joining to the chat
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
common.LogErrorln("Error upgrading to websocket:", err)
return
}
common.LogDebugln("Connection has been upgraded to websocket")
chatConn := &chatConnection{
Conn: conn,
// If the server is behind a reverse proxy (eg, Nginx), look
// for this header to get the real IP address of the client.
forwardedFor: common.ExtractForwarded(r),
}
go func() {
var client *Client
// Get the client object
for client == nil {
var data common.ClientData
err := chatConn.ReadData(&data)
if err != nil {
common.LogInfof("[handler] Client closed connection: %s: %v\n",
conn.RemoteAddr().String(), err)
conn.Close()
return
}
if data.Type == common.CdPing {
continue
}
var joinData common.JoinData
err = json.Unmarshal([]byte(data.Message), &joinData)
if err != nil {
common.LogInfof("[handler] Could not unmarshal websocket %d data %#v: %v\n", data.Type, data.Message, err)
continue
}
client, err = chat.Join(chatConn, joinData)
if err != nil {
switch err.(type) { //nolint:errorlint
case UserFormatError, UserTakenError:
common.LogInfof("[handler|%s] %v\n", errorName(err), err)
case BannedUserError:
common.LogInfof("[handler|%s] %v\n", errorName(err), err)
// close connection since banned users shouldn't be connecting
conn.Close()
default:
// for now all errors not caught need to be warned
common.LogErrorf("[handler|uncaught] %v\n", err)
conn.Close()
}
}
}
// Handle incomming messages
for {
var data common.ClientData
err := conn.ReadJSON(&data)
if err != nil { //if error then assuming that the connection is closed
client.Exit()
return
}
client.NewMsg(data)
}
}()
}
// returns if it's OK to proceed
func checkRoomAccess(w http.ResponseWriter, r *http.Request) bool {
session, err := sstore.Get(r, "moviesession")
if err != nil {
// Don't return as server error here, just make a new session.
common.LogErrorf("Unable to get session for client %s: %v\n", r.RemoteAddr, err)
}
if settings.RoomAccess == AccessPin {
pin := session.Values["pin"]
// No pin found in session
if pin == nil || len(pin.(string)) == 0 {
if r.Method == "POST" {
// Check for correct pin
err = r.ParseForm()
if err != nil {
common.LogErrorf("Error parsing form")
http.Error(w, "Unable to get session data", http.StatusInternalServerError)
}
postPin := strings.TrimSpace(r.Form.Get("txtInput"))
common.LogDebugf("Received pin: %s\n", postPin)
if postPin == settings.RoomAccessPin {
// Pin is correct. Save it to session and return true.
session.Values["pin"] = settings.RoomAccessPin
err = session.Save(r, w)
if err != nil {
common.LogErrorf("Could not save pin cookie: %v\n", err)
return false
}
return true
}
// Pin is incorrect.
handlePinTemplate(w, r, "Incorrect PIN")
return false
} else {
qpin := r.URL.Query().Get("pin")
if qpin != "" && qpin == settings.RoomAccessPin {
// Pin is correct. Save it to session and return true.
session.Values["pin"] = settings.RoomAccessPin
err = session.Save(r, w)
if err != nil {
common.LogErrorf("Could not save pin cookie: %v\n", err)
return false
}
return true
}
}
// nope. display pin entry and return
handlePinTemplate(w, r, "")
return false
}
// Pin found in session, but it has changed since last time.
if pin.(string) != settings.RoomAccessPin {
// Clear out the old pin.
session.Values["pin"] = nil
err = session.Save(r, w)
if err != nil {
common.LogErrorf("Could not clear pin cookie: %v\n", err)
}
// Prompt for new one.
handlePinTemplate(w, r, "Pin has changed. Enter new PIN.")
return false
}
// Correct pin found in session
return true
}
// TODO: this.
if settings.RoomAccess == AccessRequest {
http.Error(w, "Requesting access not implemented yet", http.StatusNotImplemented)
return false
}
// Room is open.
return true
}
func handlePinTemplate(w http.ResponseWriter, r *http.Request, errorMessage string) {
type Data struct {
Title string
SubmitText string
Notice string
}
if errorMessage == "" {
errorMessage = "Please enter the PIN"
}
data := Data{
Title: "Enter Pin",
SubmitText: "Submit Pin",
Notice: errorMessage,
}
err := common.ExecuteServerTemplate(w, "pin", data)
if err != nil {
common.LogErrorf("Error executing file, %v", err)
}
}
func handleHelpTemplate(w http.ResponseWriter, r *http.Request) {
type Data struct {
Title string
Commands map[string]string
ModCommands map[string]string
AdminCommands map[string]string
}
data := Data{
Title: "Help",
Commands: getHelp(common.CmdlUser),
}
if len(r.URL.Query().Get("mod")) > 0 {
data.ModCommands = getHelp(common.CmdlMod)
}
if len(r.URL.Query().Get("admin")) > 0 {
data.AdminCommands = getHelp(common.CmdlAdmin)
}
err := common.ExecuteServerTemplate(w, "help", data)
if err != nil {
common.LogErrorf("Error executing file, %v", err)
}
}
func handleEmoteTemplate(w http.ResponseWriter, r *http.Request) {
type Data struct {
Title string
Emotes map[string]string
}
data := Data{
Title: "Available Emotes",
Emotes: common.Emotes,
}
common.LogDebugf("Emotes Data: %s", data)
err := common.ExecuteServerTemplate(w, "emotes", data)
if err != nil {
common.LogErrorf("Error executing file, %v", err)
}
}
func handleIndexTemplate(w http.ResponseWriter, r *http.Request) {
type Data struct {
Video, Chat bool
MessageHistoryCount int
Title string
}
data := Data{
Video: true,
Chat: true,
MessageHistoryCount: settings.MaxMessageCount,
Title: settings.PageTitle,
}
path := strings.Split(strings.TrimLeft(r.URL.Path, "/"), "/")
if path[0] == "chat" {
data.Video = false
data.Title += " - chat"
} else if path[0] == "video" {
data.Chat = false
data.Title += " - video"
}
// Force browser to replace cache since file was not changed
if settings.NoCache {
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
}
err := common.ExecuteServerTemplate(w, "main", data)
if err != nil {
common.LogErrorf("Error executing file, %v", err)
}
}
func handlePublish(conn *rtmp.Conn) {
streams, _ := conn.Streams()
l.Lock()
common.LogDebugln("request string->", conn.URL.RequestURI())
urlParts := strings.Split(strings.Trim(conn.URL.RequestURI(), "/"), "/")
common.LogDebugln("urlParts->", urlParts)
if len(urlParts) > 2 {
common.LogErrorln("Extra garbage after stream key")
l.Unlock()
conn.Close()
return
}
if len(urlParts) != 2 {
common.LogErrorln("Missing stream key")
l.Unlock()
conn.Close()
return
}
if urlParts[1] != settings.GetStreamKey() {
common.LogErrorln("Stream key is incorrect. Denying stream.")
l.Unlock()
conn.Close()
return //If key not match, deny stream
}
streamPath := urlParts[0]
_, exists := channels[streamPath]
if exists {
common.LogErrorln("Stream already running. Denying publish.")
conn.Close()
l.Unlock()
return
}
ch := &Channel{}
ch.que = pubsub.NewQueue()
err := ch.que.WriteHeader(streams)
if err != nil {
common.LogErrorf("Could not write header to streams: %v\n", err)
}
channels[streamPath] = ch
l.Unlock()
stats.startStream()
common.LogInfoln("Stream started")
err = avutil.CopyPackets(ch.que, conn)
if err != nil {
common.LogErrorf("Could not copy packets to connections: %v\n", err)
}
common.LogInfoln("Stream finished")
stats.endStream()
l.Lock()
delete(channels, streamPath)
l.Unlock()
ch.que.Close()
}
func handlePlay(conn *rtmp.Conn) {
l.RLock()
ch := channels[conn.URL.Path]
l.RUnlock()
if ch != nil {
cursor := ch.que.Latest()
err := avutil.CopyFile(conn, cursor)
if err != nil {
common.LogErrorf("Could not copy video to connection: %v\n", err)
}
}
}
func handleLive(w http.ResponseWriter, r *http.Request) {
l.RLock()
ch := channels[strings.Trim(r.URL.Path, "/")]
l.RUnlock()
if ch != nil {
w.Header().Set("Content-Type", "video/x-flv")
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(200)
flusher := w.(http.Flusher)
flusher.Flush()
muxer := flv.NewMuxerWriteFlusher(writeFlusher{httpflusher: flusher, Writer: w})
cursor := ch.que.Latest()
session, _ := sstore.Get(r, "moviesession")
stats.addViewer(session.ID)
err := avutil.CopyFile(muxer, cursor)
if err != nil {
common.LogErrorf("Could not copy video to connection: %v\n", err)
}
stats.removeViewer(session.ID)
} else {
// Maybe HTTP_204 is better than HTTP_404
w.WriteHeader(http.StatusNoContent)
stats.resetViewers()
}
}
func handleDefault(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
// not really an error for the server, but for the client.
common.LogInfoln("[http 404] ", r.URL.Path)
http.NotFound(w, r)
} else {
handleIndexTemplate(w, r)
}
}
func wrapAuth(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if settings.RoomAccess != AccessOpen {
if !checkRoomAccess(w, r) {
common.LogDebugln("Denied access")
return
}
common.LogDebugln("Granted access")
}
next.ServeHTTP(w, r)
})
}