-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
377 lines (335 loc) · 8.89 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
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
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"sort"
"sync"
)
var (
mu sync.Mutex
currentIndex int
filesA []string
filesB []string
)
// SSE client management.
var (
sseMu sync.Mutex
sseClients = make(map[chan string]bool)
)
// Templates.
var (
fullPageTmpl = template.Must(template.New("fullPage").Parse(fullPageHTML))
contentTmpl = template.Must(template.New("content").Parse(contentTemplateHTML))
)
// Full page template includes htmx, SSE connection, a click overlay, and keydown listener for full screen toggling.
const fullPageHTML = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{.Title}}</title>
<script src="https://unpkg.com/[email protected]"></script>
<style>
html, body { margin: 0; padding: 0; height: 100%; background: black; }
/* The overlay captures clicks to advance the slide */
#click-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 999;
cursor: pointer;
}
</style>
</head>
<body hx-sse="connect:/sse">
<!-- This container is updated via htmx on load and when a "mediaChanged" SSE event is received -->
<div id="media-container" hx-get="{{.ContentURL}}" hx-trigger="load, sse:mediaChanged" hx-swap="innerHTML">
Loading...
</div>
<!-- A transparent overlay to capture clicks -->
<div id="click-overlay" hx-post="/advance" hx-trigger="click" hx-swap="none"></div>
<script>
// Toggle full screen mode when 'f' (or 'F') is pressed.
document.addEventListener("keydown", function(e) {
if (e.key === "f" || e.key === "F") {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen().catch(err => {
console.error("Error enabling full-screen mode:", err);
});
} else {
document.exitFullscreen();
}
}
if (e.key === "ArrowLeft") {
fetch("/previous", {method: "POST"})
}
if (e.key === "ArrowRight") {
fetch("/advance", {method: "POST"})
}
if (e.key === "r" || e.key === "R") {
fetch("/reload", {method: "POST"})
}
if (e.key === "0") {
fetch("/reset", {method: "POST"})
}
});
</script>
</body>
</html>
`
// Partial template to render the media element.
const contentTemplateHTML = `
{{if .IsVideo}}
<video autoplay loop style="width:100%; height:100%; object-fit:contain;" src="{{.MediaSrc}}"></video>
{{else}}
<img style="width:100%; height:100%; object-fit:contain;" src="{{.MediaSrc}}" alt="media">
{{end}}
`
func main() {
var err error
// Load and sort media files for displays A and B.
filesA, err = loadFiles("./data/a")
if err != nil {
log.Fatal("Error loading ./data/a: ", err)
}
filesB, err = loadFiles("./data/b")
if err != nil {
log.Fatal("Error loading ./data/b: ", err)
}
if len(filesA) == 0 || len(filesB) == 0 {
log.Fatal("No files found in one of the directories.")
}
// Route handlers.
http.HandleFunc("/a", serveA)
http.HandleFunc("/b", serveB)
http.HandleFunc("/content/a", contentA)
http.HandleFunc("/content/b", contentB)
http.HandleFunc("/reset", resetHandler)
http.HandleFunc("/reload", reloadHandler)
http.HandleFunc("/advance", advanceHandler)
http.HandleFunc("/previous", previousHandler)
http.HandleFunc("/sse", sseHandler)
// Serve static media files.
http.Handle("/static/a/", http.StripPrefix("/static/a/", http.FileServer(http.Dir("./data/a"))))
http.Handle("/static/b/", http.StripPrefix("/static/b/", http.FileServer(http.Dir("./data/b"))))
port := ":8080"
log.Println("Server started on port", port)
log.Fatal(http.ListenAndServe(port, nil))
}
// loadFiles returns a sorted list of file names in the specified directory.
func loadFiles(dir string) ([]string, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
var files []string
for _, entry := range entries {
if !entry.IsDir() && isMedia(entry.Name()) {
files = append(files, entry.Name())
}
}
sort.Strings(files)
return files, nil
}
// serveA renders the full page for Display A.
func serveA(w http.ResponseWriter, r *http.Request) {
data := struct {
Title string
ContentURL string
}{
Title: "Display A",
ContentURL: "/content/a",
}
fullPageTmpl.Execute(w, data)
}
// serveB renders the full page for Display B.
func serveB(w http.ResponseWriter, r *http.Request) {
data := struct {
Title string
ContentURL string
}{
Title: "Display B",
ContentURL: "/content/b",
}
fullPageTmpl.Execute(w, data)
}
// contentA returns the media snippet for Display A.
func contentA(w http.ResponseWriter, r *http.Request) {
mu.Lock()
idx := currentIndex
mu.Unlock()
log.Printf("index: %d/n", idx)
fileName := filesA[idx%len(filesA)]
mediaSrc := "/static/a/" + fileName
data := struct {
MediaSrc string
IsVideo bool
}{
MediaSrc: mediaSrc,
IsVideo: isVideo(fileName),
}
contentTmpl.Execute(w, data)
}
// contentB returns the media snippet for Display B.
func contentB(w http.ResponseWriter, r *http.Request) {
mu.Lock()
idx := currentIndex
mu.Unlock()
fileName := filesB[idx%len(filesB)]
mediaSrc := "/static/b/" + fileName
data := struct {
MediaSrc string
IsVideo bool
}{
MediaSrc: mediaSrc,
IsVideo: isVideo(fileName),
}
contentTmpl.Execute(w, data)
}
// isVideo checks if a file extension indicates a video file.
func isVideo(fileName string) bool {
ext := filepath.Ext(fileName)
switch ext {
case ".mp4", ".webm", ".ogg", ".mov", ".m4v":
return true
default:
return false
}
}
// resetHandler increments the global index and broadcasts an SSE event.
func resetHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("advanced")
if r.Method != http.MethodPost {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
mu.Lock()
currentIndex = 0
mu.Unlock()
// Broadcast the "mediaChanged" event to all connected clients.
broadcastSSE("mediaChanged")
w.WriteHeader(http.StatusOK)
}
// resetHandler increments the global index and broadcasts an SSE event.
func reloadHandler(w http.ResponseWriter, r *http.Request) {
var err error
mu.Lock()
filesA, err = loadFiles("./data/a")
if err != nil {
log.Fatal("Error loading ./data/a: ", err)
}
mu.Unlock()
mu.Lock()
filesB, err = loadFiles("./data/b")
if err != nil {
log.Fatal("Error loading ./data/b: ", err)
}
mu.Unlock()
if len(filesA) == 0 || len(filesB) == 0 {
log.Fatal("No files found in one of the directories.")
}
if r.Method != http.MethodPost {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
mu.Lock()
currentIndex = 0
mu.Unlock()
// Broadcast the "mediaChanged" event to all connected clients.
broadcastSSE("mediaChanged")
w.WriteHeader(http.StatusOK)
}
// advanceHandler increments the global index and broadcasts an SSE event.
func advanceHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("advanced")
if r.Method != http.MethodPost {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
mu.Lock()
currentIndex++
mu.Unlock()
// Broadcast the "mediaChanged" event to all connected clients.
broadcastSSE("mediaChanged")
w.WriteHeader(http.StatusOK)
}
// previousHandler decrements the global index and broadcasts an SSE event.
func previousHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("advanced")
if r.Method != http.MethodPost {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
mu.Lock()
currentIndex--
if currentIndex < 0 {
currentIndex = 0
}
mu.Unlock()
// Broadcast the "mediaChanged" event to all connected clients.
broadcastSSE("mediaChanged")
w.WriteHeader(http.StatusOK)
}
// sseHandler implements a simple Server-Sent Events endpoint.
func sseHandler(w http.ResponseWriter, r *http.Request) {
// Set necessary headers for SSE.
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
// Create a channel for this client.
messageChan := make(chan string, 10)
// Register the client.
sseMu.Lock()
sseClients[messageChan] = true
sseMu.Unlock()
// Ensure client removal on disconnect.
defer func() {
sseMu.Lock()
delete(sseClients, messageChan)
sseMu.Unlock()
}()
notify := r.Context().Done()
for {
select {
case msg := <-messageChan:
fmt.Fprintf(w, "event: %s\n", msg)
fmt.Fprintf(w, "data: %s\n\n", msg)
flusher.Flush()
case <-notify:
return
}
}
}
// broadcastSSE sends the specified message to all connected SSE clients.
func broadcastSSE(message string) {
sseMu.Lock()
defer sseMu.Unlock()
for ch := range sseClients {
select {
case ch <- message:
default:
// If the client's channel is full, skip sending.
}
}
}
func isMedia(fileName string) bool {
switch filepath.Ext(fileName) {
case ".jpg", ".png", ".jpeg":
return true
case ".mp4", ".webm", ".ogg", ".mov", ".m4v":
return true
default:
return false
}
}