-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.go
More file actions
160 lines (140 loc) · 4.5 KB
/
tracker.go
File metadata and controls
160 lines (140 loc) · 4.5 KB
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
package main
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis/v7"
"log"
"net/http"
"time"
)
type StreamTracker struct {
password string
mapper *StreamMapper
redis *redis.Client
mux *http.ServeMux
}
func NewStreamTracker(mapper *StreamMapper, redis *redis.Client, password string) *StreamTracker {
st := &StreamTracker{
password: password,
mapper: mapper,
redis: redis,
mux: http.NewServeMux(),
}
st.mux.HandleFunc("/notify/publish", st.handlePublish)
st.mux.HandleFunc("/notify/publish_done", st.handlePublishDone)
st.mux.HandleFunc("/api/streams", st.handleStreams)
st.mux.HandleFunc("/api/outputs", st.handleOutputs)
st.mux.HandleFunc("/api/stream_updates", st.handleStreamUpdates)
return st
}
func (st *StreamTracker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
st.mux.ServeHTTP(w, r)
}
func (st *StreamTracker) handlePublish(w http.ResponseWriter, r *http.Request) {
key := r.PostFormValue("name")
if !st.mapper.HasStreamKey(key) {
http.Error(w, "Invalid key", http.StatusNotFound)
return
}
if err := st.redis.HSet("active_streams", key, "1").Err(); err != nil {
log.Printf("Failed to update stream activity: %v\n", err)
}
name := st.mapper.StreamNameFromKey(key)
if name != "" {
if err := st.redis.Publish("stream_activity", "1|"+name).Err(); err != nil {
log.Printf("Failed to publish stream update: %v\n", err)
}
}
_, _ = w.Write([]byte("ok"))
}
func (st *StreamTracker) handlePublishDone(w http.ResponseWriter, r *http.Request) {
key := r.PostFormValue("name")
if err := st.redis.HDel("active_streams", key).Err(); err != nil {
log.Printf("Failed to update stream activity: %v\n", err)
}
name := st.mapper.StreamNameFromKey(key)
if name != "" {
if err := st.redis.Publish("stream_activity", "0|"+name).Err(); err != nil {
log.Printf("Failed to publish stream update: %v\n", err)
}
}
_, _ = w.Write([]byte("ok"))
}
type stream struct {
Key string `json:"key"`
Live bool `json:"live"`
}
type liveStreams struct {
Streams map[string]stream `json:"streams"`
}
func (st *StreamTracker) handleStreams(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
if st.password != "" && r.URL.Query().Get("password") != st.password {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
active, err := st.redis.HGetAll("active_streams").Result()
if err != nil {
log.Printf("Couldn't look up active streams: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ls := liveStreams{Streams: map[string]stream{}}
for k, v := range st.mapper.GetStreams() {
ls.Streams[k] = stream{Key: v, Live: active[v] == "1"}
}
if err := json.NewEncoder(w).Encode(ls); err != nil {
log.Printf("Couldn't encode active streams: %v??\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (st *StreamTracker) handleOutputs(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
if st.password != "" && r.URL.Query().Get("password") != st.password {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
out := struct {
Outputs []Output `json:"outputs"`
}{st.mapper.GetOutputs()}
if err := json.NewEncoder(w).Encode(out); err != nil {
log.Printf("Couldn't encode outputs: %v??\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (st *StreamTracker) handleStreamUpdates(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
if st.password != "" && r.URL.Query().Get("password") != st.password {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("X-Accel-Buffering", "no")
pubsub := st.redis.Subscribe("stream_activity")
defer pubsub.Close()
_, _ = w.Write([]byte(": hello\n\n"))
w.(http.Flusher).Flush()
const pingTime = 45 * time.Second
pingChannel := time.After(pingTime)
for {
output := ""
select {
case message := <-pubsub.Channel():
output = fmt.Sprintf("data: %s\n\n", message.Payload)
case <-pingChannel:
pingChannel = time.After(pingTime)
output = ": ping\n\n"
}
_, err := w.Write([]byte(output))
if err == nil {
w.(http.Flusher).Flush()
} else {
log.Printf("write failed, dropping connection: %v", err)
break
}
}
}