-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
691 lines (592 loc) · 19.2 KB
/
main.go
File metadata and controls
691 lines (592 loc) · 19.2 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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
package main
import (
"encoding/base64"
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/gorilla/websocket"
"github.com/patrickmn/go-cache"
)
// Quickview - Real-time media viewer with customizable grid layouts
type App struct {
images map[string]string // position -> base64 image
filenames map[string]string // position -> filename
imageCount int // total images loaded
mu sync.RWMutex
clients []*Client
clientsMu sync.RWMutex
filenameCache *cache.Cache
}
type Client struct {
conn *websocket.Conn
id int
gridWidth int
gridHeight int
frames int
paused map[string]bool
pausedMu sync.RWMutex
}
type Message struct {
Type string `json:"type"`
Position string `json:"position"`
Paused bool `json:"paused"`
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var nextClientID int
var clientIDMu sync.Mutex
var htmlTemplate = `
<!DOCTYPE html>
<html>
<head>
<title>Quickview</title>
<style>
/* Grid layout */
body {
margin: 0;
padding: 0;
display: grid;
grid-template-columns: repeat({{.GridWidth}}, 1fr);
grid-template-rows: repeat({{.GridHeight}}, 1fr);
height: 100vh;
background: #222;
font-family: Arial, sans-serif;
overflow: hidden;
}
.image-container {
position: relative;
overflow: hidden;
border: 2px solid #444;
box-sizing: border-box;
cursor: pointer;
transition: border-color 0.3s;
}
.image-container.paused {
border-color: #f44;
}
img, video {
width: 100%;
height: 100%;
object-fit: {{.ObjectFit}};
opacity: 1;
transition: opacity 0.3s ease-in-out;
}
img.fade-out, video.fade-out {
opacity: 0;
}
.empty {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #666;
text-align: center;
}
.pause-indicator {
position: absolute;
top: 10px;
right: 10px;
background: rgba(244, 67, 54, 0.9);
color: white;
padding: 5px 10px;
border-radius: 3px;
font-size: 12px;
opacity: 0;
transition: opacity 0.3s;
}
.image-container.paused .pause-indicator {
opacity: 1;
}
.status {
position: absolute;
top: 10px;
left: 10px;
padding: 5px 10px;
background: rgba(0, 0, 0, 0.7);
color: #0f0;
border-radius: 3px;
font-size: 12px;
z-index: 10;
}
.status.disconnected {
color: #f00;
}
.filename {
position: absolute;
bottom: 10px;
left: 10px;
padding: 5px 10px;
background: rgba(0, 0, 0, 0.7);
color: #fff;
border-radius: 3px;
font-size: 12px;
}
</style>
</head>
<body>
{{range .Positions}}
<div class="image-container" data-position="{{.}}">
<img id="{{.}}-image" style="display: none;" alt="{{.}}">
<video id="{{.}}-video" style="display: none;" autoplay muted loop playsinline></video>
<div id="{{.}}-empty" class="empty">Waiting for media...<br><small>Click to pause</small></div>
<div class="pause-indicator">PAUSED</div>
<div id="{{.}}-filename" class="filename" style="display: none;"></div>
</div>
{{end}}
<div id="status" class="status">Connecting...</div>
<script>
let ws;
let reconnectTimeout;
let pausedFrames = new Set();
function updateImage(position, imageData, filename) {
const container = document.querySelector('[data-position="' + position + '"]');
const img = document.getElementById(position + '-image');
const video = document.getElementById(position + '-video');
const empty = document.getElementById(position + '-empty');
const filenameEl = document.getElementById(position + '-filename');
if (imageData && !pausedFrames.has(position)) {
// Determine if this is a video based on filename
const isVideo = filename && filename.toLowerCase().endsWith('.mp4');
// Fade out current content
img.classList.add('fade-out');
video.classList.add('fade-out');
setTimeout(() => {
if (isVideo) {
// Clean up previous video to free memory
if (video.src) {
video.pause();
video.removeAttribute('src');
video.load();
}
// Hide image, show video
img.style.display = 'none';
video.src = 'data:video/mp4;base64,' + imageData;
video.style.display = 'block';
empty.style.display = 'none';
video.classList.remove('fade-out');
} else {
// Clean up video if it was playing
if (video.style.display === 'block') {
video.pause();
video.removeAttribute('src');
video.load();
}
// Hide video, show image
video.style.display = 'none';
img.src = 'data:image/png;base64,' + imageData;
img.style.display = 'block';
empty.style.display = 'none';
img.classList.remove('fade-out');
}
// Update filename if provided
if (filename && filenameEl) {
filenameEl.textContent = filename;
filenameEl.style.display = 'block';
}
}, 300);
}
}
function togglePause(position) {
const container = document.querySelector('[data-position="' + position + '"]');
const video = document.getElementById(position + '-video');
const isPaused = pausedFrames.has(position);
if (isPaused) {
pausedFrames.delete(position);
container.classList.remove('paused');
// Resume video if present
if (video.style.display === 'block') {
video.play();
}
} else {
pausedFrames.add(position);
container.classList.add('paused');
// Pause video if present
if (video.style.display === 'block') {
video.pause();
}
}
// Send pause state to server
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: 'pause',
position: position,
paused: !isPaused
}));
}
}
function connect() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
ws = new WebSocket(protocol + '//' + window.location.host + '/ws?width={{.GridWidth}}&height={{.GridHeight}}');
ws.onopen = () => {
console.log('WebSocket connected');
document.getElementById('status').textContent = 'Connected';
document.getElementById('status').classList.remove('disconnected');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'init') {
// Update window title with ID
document.title = 'Quickview - Window ' + data.clientId;
} else if (data.type === 'image') {
updateImage(data.position, data.image, data.filename);
} else if (data.type === 'windowCount') {
// Window count is no longer displayed
}
};
ws.onclose = () => {
console.log('WebSocket disconnected');
document.getElementById('status').textContent = 'Disconnected';
document.getElementById('status').classList.add('disconnected');
clearTimeout(reconnectTimeout);
reconnectTimeout = setTimeout(connect, 2000);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
// Add click handlers
document.querySelectorAll('.image-container').forEach(container => {
container.addEventListener('click', () => {
const position = container.dataset.position;
togglePause(position);
});
});
// Add window unload handler to clean up videos
window.addEventListener('beforeunload', () => {
// Clean up all videos before leaving
document.querySelectorAll('video').forEach(video => {
video.pause();
video.removeAttribute('src');
video.load();
});
});
connect();
</script>
</body>
</html>
`
func main() {
watchDir := flag.String("dir", ".", "Directory to watch for media files")
extensions := flag.String("ext", "png,jpg,jpeg,gif,mp4", "File extensions to watch (comma separated)")
port := flag.String("port", "8080", "Port for web server")
defaultWidth := flag.Int("width", 3, "Default grid width (1-10)")
defaultHeight := flag.Int("height", 1, "Default grid height (1-10)")
flag.Parse()
extList := strings.Split(*extensions, ",")
for i := range extList {
extList[i] = "." + strings.TrimSpace(extList[i])
}
app := &App{
images: make(map[string]string),
filenames: make(map[string]string),
imageCount: 0,
clients: make([]*Client, 0),
filenameCache: cache.New(1*time.Second, 2*time.Second),
}
go app.watchFolder(*watchDir, extList)
tmpl := template.Must(template.New("viewer").Parse(htmlTemplate))
// Serve HTML page with grid dimensions
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
widthStr := r.URL.Query().Get("width")
heightStr := r.URL.Query().Get("height")
// Default to configured grid size
gridWidth := *defaultWidth
gridHeight := *defaultHeight
if widthStr != "" {
if w, err := strconv.Atoi(widthStr); err == nil && w > 0 && w <= 10 {
gridWidth = w
}
}
if heightStr != "" {
if h, err := strconv.Atoi(heightStr); err == nil && h > 0 && h <= 10 {
gridHeight = h
}
}
objectFit := r.URL.Query().Get("fit")
if objectFit == "" {
objectFit = "cover"
}
// Generate position names for the grid
positions := make([]string, 0, gridWidth*gridHeight)
for row := 0; row < gridHeight; row++ {
for col := 0; col < gridWidth; col++ {
positions = append(positions, fmt.Sprintf("r%dc%d", row, col))
}
}
data := struct {
GridWidth int
GridHeight int
Positions []string
ObjectFit string
}{
GridWidth: gridWidth,
GridHeight: gridHeight,
Positions: positions,
ObjectFit: objectFit,
}
tmpl.Execute(w, data)
})
// WebSocket endpoint
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("WebSocket upgrade error: %v", err)
return
}
defer conn.Close()
widthStr := r.URL.Query().Get("width")
heightStr := r.URL.Query().Get("height")
// Default to configured grid size
gridWidth := *defaultWidth
gridHeight := *defaultHeight
if widthStr != "" {
if w, err := strconv.Atoi(widthStr); err == nil && w > 0 && w <= 10 {
gridWidth = w
}
}
if heightStr != "" {
if h, err := strconv.Atoi(heightStr); err == nil && h > 0 && h <= 10 {
gridHeight = h
}
}
frames := gridWidth * gridHeight
clientIDMu.Lock()
clientID := nextClientID
nextClientID++
clientIDMu.Unlock()
client := &Client{
conn: conn,
id: clientID,
gridWidth: gridWidth,
gridHeight: gridHeight,
frames: frames,
paused: make(map[string]bool),
}
// Send client ID
conn.WriteJSON(map[string]interface{}{
"type": "init",
"clientId": clientID,
})
app.clientsMu.Lock()
app.clients = append(app.clients, client)
clientCount := len(app.clients)
app.clientsMu.Unlock()
// Broadcast window count to all clients
app.broadcastWindowCount(clientCount)
app.sendCurrentImages(client)
// Handle messages from client
for {
var msg Message
err := conn.ReadJSON(&msg)
if err != nil {
break
}
if msg.Type == "pause" {
client.pausedMu.Lock()
client.paused[msg.Position] = msg.Paused
client.pausedMu.Unlock()
}
}
// Remove client on disconnect
app.clientsMu.Lock()
for i, c := range app.clients {
if c == client {
app.clients = append(app.clients[:i], app.clients[i+1:]...)
break
}
}
newClientCount := len(app.clients)
app.clientsMu.Unlock()
// Broadcast updated window count
app.broadcastWindowCount(newClientCount)
})
fmt.Printf("Starting Quickview on http://localhost:%s\n", *port)
fmt.Printf("Watching %s for files with extensions: %v\n", *watchDir, extList)
fmt.Printf("Default grid: %dx%d\n", *defaultWidth, *defaultHeight)
fmt.Println("\nGrid dimensions (use ?width=X&height=Y in URL):")
fmt.Printf(" Default: http://localhost:%s (%dx%d grid)\n", *port, *defaultWidth, *defaultHeight)
fmt.Println(" Examples:")
fmt.Println(" 2x2 grid: http://localhost:" + *port + "/?width=2&height=2")
fmt.Println(" 4x3 grid: http://localhost:" + *port + "/?width=4&height=3")
fmt.Println(" 1x4 vertical: http://localhost:" + *port + "/?width=1&height=4")
fmt.Println(" Maximum: 10x10 grid")
fmt.Println("\nMedia fit options (add &fit= to URL):")
fmt.Println(" cover (default) - fills frame, crops if needed")
fmt.Println(" contain - shows entire media, may have bars")
fmt.Println(" fill - stretches to fill")
fmt.Println(" scale-down - like contain but never enlarges")
fmt.Println("\nExample: http://localhost:" + *port + "/?width=3&height=2&fit=contain")
fmt.Println("\nSupported media: Images (png, jpg, jpeg, gif) and Videos (mp4)")
fmt.Println("Videos play automatically, muted, and loop")
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
func (a *App) broadcastWindowCount(count int) {
a.clientsMu.RLock()
defer a.clientsMu.RUnlock()
for _, client := range a.clients {
client.conn.WriteJSON(map[string]interface{}{
"type": "windowCount",
"count": count,
})
}
}
func (a *App) sendCurrentImages(client *Client) {
a.mu.RLock()
defer a.mu.RUnlock()
positions := a.getPositionsForGrid(client.gridWidth, client.gridHeight)
for _, position := range positions {
if image, exists := a.images[position]; exists && image != "" {
client.pausedMu.RLock()
isPaused := client.paused[position]
client.pausedMu.RUnlock()
if !isPaused {
msg := map[string]interface{}{
"type": "image",
"position": position,
"image": image,
}
// Add filename if available
if filename, hasFilename := a.filenames[position]; hasFilename {
msg["filename"] = filename
}
client.conn.WriteJSON(msg)
}
}
}
}
func (a *App) watchFolder(dir string, extensions []string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal("Error creating watcher:", err)
}
defer watcher.Close()
err = watcher.Add(dir)
if err != nil {
log.Fatal("Error watching directory:", err)
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Create == fsnotify.Create ||
event.Op&fsnotify.Write == fsnotify.Write {
if isMediaFile(event.Name, extensions) {
fmt.Printf("Quickview: New media detected: %s\n", filepath.Base(event.Name))
a.loadMedia(event.Name)
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("Watcher error:", err)
}
}
}
func (a *App) loadMedia(imagePath string) {
file, err := os.Open(imagePath)
if err != nil {
log.Printf("Error opening media %s: %v", imagePath, err)
return
}
defer file.Close()
data, err := io.ReadAll(file)
if err != nil {
log.Printf("Error reading media %s: %v", imagePath, err)
return
}
// skip if no media data
if len(data) == 0 {
return
}
// skip if already processed
_, found := a.filenameCache.Get(imagePath)
if found {
fmt.Printf("Quickview: Skipping - %s already processed\n", filepath.Base(imagePath))
return
}
a.filenameCache.SetDefault(imagePath, true)
encoded := base64.StdEncoding.EncodeToString(data)
// Find next available frame across all windows
a.clientsMu.RLock()
defer a.clientsMu.RUnlock()
if len(a.clients) == 0 {
return
}
// Build list of all available (non-paused) frames
framePositions := make([]struct {
client *Client
position string
}, 0)
for _, client := range a.clients {
positions := a.getPositionsForGrid(client.gridWidth, client.gridHeight)
for _, pos := range positions {
client.pausedMu.RLock()
isPaused := client.paused[pos]
client.pausedMu.RUnlock()
if !isPaused {
framePositions = append(framePositions, struct {
client *Client
position string
}{client, pos})
}
}
}
if len(framePositions) == 0 {
log.Println("All frames are paused")
return
}
// Find which frame to update (round-robin)
a.mu.Lock()
nextIndex := a.imageCount % len(framePositions)
a.imageCount++
frame := framePositions[nextIndex]
// Store image and filename
a.images[frame.position] = encoded
a.filenames[frame.position] = filepath.Base(imagePath)
a.mu.Unlock()
// Send to the specific client
frame.client.conn.WriteJSON(map[string]interface{}{
"type": "image",
"position": frame.position,
"image": encoded,
"filename": filepath.Base(imagePath),
})
}
func (a *App) getPositionsForGrid(gridWidth, gridHeight int) []string {
positions := make([]string, 0, gridWidth*gridHeight)
for row := 0; row < gridHeight; row++ {
for col := 0; col < gridWidth; col++ {
positions = append(positions, fmt.Sprintf("r%dc%d", row, col))
}
}
return positions
}
func isMediaFile(filename string, extensions []string) bool {
ext := strings.ToLower(filepath.Ext(filename))
for _, validExt := range extensions {
if ext == strings.ToLower(validExt) {
return true
}
}
return false
}
func isVideoFile(filename string) bool {
ext := strings.ToLower(filepath.Ext(filename))
return ext == ".mp4"
}