-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscribe.go
78 lines (66 loc) · 1.86 KB
/
subscribe.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
package liveshare_routes
import (
"bufio"
"fmt"
"github.com/Liphium/station/chatserver/liveshare"
"github.com/Liphium/station/chatserver/util"
"github.com/Liphium/station/main/integration"
"github.com/gofiber/fiber/v2"
"github.com/valyala/fasthttp"
)
func subscribeToLiveshare(c *fiber.Ctx) error {
id := c.FormValue("id", "")
token := c.FormValue("token", "")
if id == "" || token == "" {
return integration.InvalidRequest(c, "id and token are required")
}
receiver, valid := liveshare.NewTransactionReceiver(id, token)
if !valid {
return integration.InvalidRequest(c, "Invalid id or token")
}
c.Set("Content-Type", "text/event-stream")
c.Set("Cache-Control", "no-cache")
c.Set("Connection", "keep-alive")
c.Set("Transfer-Encoding", "chunked")
c.Context().SetBodyStreamWriter(fasthttp.StreamWriter(func(w *bufio.Writer) {
util.Log.Println("Started subscription, waiting for packets...")
defer func() {
if err := recover(); err != nil {
util.Log.Println("Recovered from panic: ", err)
}
util.Log.Println("Cancelling liveshare session")
liveshare.CancelTransaction(id)
}()
// Send chunk start packet
_, err := fmt.Fprintf(w, "data: %s\n\n", receiver.ReceiverId)
if err != nil {
util.Log.Println("Error while writing: ", err)
return
}
err = w.Flush()
if err != nil {
util.Log.Println("Error while flushing: ", err)
return
}
for {
packet := <-receiver.SendChannel
if packet == -1 {
util.Log.Println("Subscription ended")
return
}
// Send chunk data packet
written, err := fmt.Fprintf(w, "data: %d\n\n", packet)
if err != nil {
util.Log.Println("Error while writing: ", err)
return
}
util.Log.Println("Wrote", written, "bytes to", receiver.ReceiverId)
err = w.Flush()
if err != nil {
util.Log.Println("Error while flushing: ", err)
return
}
}
}))
return nil
}