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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
|
// alis.go — ALiS v1 live streaming support.
//
// Implements:
// - POST /api/v1/streams — create/activate a stream (CLI auth)
// - GET /ws/S/{producer_token} — producer WebSocket (ALiS v1)
// - GET /ws/s/{public_token} — consumer WebSocket (ALiS v1)
// - GET /s/{public_token} — live player page
package main
import (
"bytes"
"crypto/md5"
"database/sql"
"encoding/json"
"fmt"
"html/template"
"image/png"
"log"
"net/http"
"strings"
"sync"
"time"
avt "avt-go"
"golang.org/x/net/websocket"
)
// ---------------------------------------------------------------------------
// DB schema migration (called from openServer)
// ---------------------------------------------------------------------------
const streamSchema = `
CREATE TABLE IF NOT EXISTS streams (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER REFERENCES users(id),
producer_token TEXT NOT NULL UNIQUE,
public_token TEXT NOT NULL UNIQUE,
live INTEGER NOT NULL DEFAULT 0,
ended INTEGER NOT NULL DEFAULT 0,
title TEXT,
cols INTEGER,
rows INTEGER,
snapshot TEXT,
snapshot_seq INTEGER,
snapshot_time INTEGER,
inserted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS stream_chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
chunk BLOB NOT NULL,
seq_end INTEGER NOT NULL
);
`
// streamMigrations are additive ALTER TABLE migrations run after streamSchema.
// Errors are ignored (column may already exist).
var streamMigrations = []string{
`ALTER TABLE streams ADD COLUMN ended INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE streams ADD COLUMN title TEXT`,
`ALTER TABLE streams ADD COLUMN snapshot TEXT`,
`ALTER TABLE streams ADD COLUMN snapshot_seq INTEGER`,
`ALTER TABLE streams ADD COLUMN snapshot_time INTEGER`,
}
// ---------------------------------------------------------------------------
// In-memory stream hub
// ---------------------------------------------------------------------------
// StreamHub holds all active live streams keyed by producer_token.
type StreamHub struct {
mu sync.RWMutex
streams map[string]*LiveStream // keyed by producer_token
byPublic map[string]*LiveStream // keyed by public_token
}
func newStreamHub() *StreamHub {
return &StreamHub{
streams: make(map[string]*LiveStream),
byPublic: make(map[string]*LiveStream),
}
}
func (h *StreamHub) getByProducer(producerToken string) *LiveStream {
h.mu.RLock()
defer h.mu.RUnlock()
return h.streams[producerToken]
}
func (h *StreamHub) getByPublic(publicToken string) *LiveStream {
h.mu.RLock()
defer h.mu.RUnlock()
return h.byPublic[publicToken]
}
func (h *StreamHub) put(producerToken, publicToken string) *LiveStream {
h.mu.Lock()
defer h.mu.Unlock()
ls := &LiveStream{
publicToken: publicToken,
recBuf: new(bytes.Buffer),
}
h.streams[producerToken] = ls
h.byPublic[publicToken] = ls
return ls
}
func (h *StreamHub) remove(producerToken, publicToken string) {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.streams, producerToken)
delete(h.byPublic, publicToken)
}
const ringSize = 100
// LiveStream holds the live state of a single streaming session.
// The receive loop holds the lock only briefly to append to the ring buffer
// and update the VT snapshot, then releases immediately — no blocking I/O
// inside the critical section.
type LiveStream struct {
publicToken string
mu sync.Mutex
vt *avt.Vt // nil until Init received
cols int
rows int
lastEventID uint64
startTime time.Time
lastTimeMu uint64 // absolute microseconds at last event (for RelTime)
ended bool
endFrame []byte // final Init snapshot for ended streams
// eotReceived is true if the producer sent an explicit EOT — meaning the
// stream is permanently over and consumers should show "Stream ended".
// If false on disconnect, stream is just offline and may resume.
eotReceived bool
// recBuf accumulates raw ALiS wire messages for recording.
// The flush goroutine swaps this pointer every 100ms (O(1) under lock)
// and writes the old buffer to stream_chunks outside the lock.
recBuf *bytes.Buffer
lastRecSeq uint64 // lastEventID at the time of the last recBuf append
// Ring buffer of raw ALiS messages. seqID is the sequence number of the
// most recently written message; it starts at 0 (no messages yet).
// ring[seqID % ringSize] is the latest message.
// uint64 never realistically wraps.
seqID uint64
ring [ringSize][]byte
}
// appendRing appends a message to the ring buffer, increments seqID, and
// records the message for the recording flush goroutine.
// Must be called with ls.mu held.
func (ls *LiveStream) appendRing(msg []byte) {
ls.seqID++
ls.ring[ls.seqID%ringSize] = msg
ls.recBuf.Write(msg)
ls.lastRecSeq = ls.seqID
}
// readRing returns all messages since sinceSeqID (exclusive), up to ringSize.
// Returns the messages in order and the current seqID.
// Must be called with ls.mu held (or a snapshot of seqID/ring taken under lock).
func (ls *LiveStream) readRing(sinceSeqID uint64) (msgs [][]byte, currentSeqID uint64) {
currentSeqID = ls.seqID
if currentSeqID <= sinceSeqID {
return nil, currentSeqID
}
count := currentSeqID - sinceSeqID
if count > ringSize {
count = ringSize
}
msgs = make([][]byte, count)
for i := uint64(0); i < count; i++ {
idx := (currentSeqID - count + 1 + i) % ringSize
msgs[i] = ls.ring[idx]
}
return msgs, currentSeqID
}
// ---------------------------------------------------------------------------
// ALiS v1 encoding (server → consumer)
// ---------------------------------------------------------------------------
// encodeLEB128 encodes a uint64 as unsigned LEB128.
func encodeLEB128(v uint64) []byte {
var buf []byte
for {
b := byte(v & 0x7f)
v >>= 7
if v != 0 {
b |= 0x80
}
buf = append(buf, b)
if v == 0 {
break
}
}
return buf
}
// encodeALiSString encodes a UTF-8 string as LEB128-length-prefixed bytes.
func encodeALiSString(s string) []byte {
b := encodeLEB128(uint64(len(s)))
return append(b, []byte(s)...)
}
// encodeALiSMagic returns the 5-byte magic header.
func encodeALiSMagic() []byte {
return []byte{'A', 'L', 'i', 'S', 0x01}
}
// encodeALiSInit encodes an Init event (0x01).
// Theme is always 0x00 (no theme) for simplicity.
func encodeALiSInit(lastID, timeMicros, cols, rows uint64, initData string) []byte {
var b []byte
b = append(b, 0x01)
b = append(b, encodeLEB128(lastID)...)
b = append(b, encodeLEB128(timeMicros)...)
b = append(b, encodeLEB128(cols)...)
b = append(b, encodeLEB128(rows)...)
b = append(b, 0x00) // no theme
b = append(b, encodeALiSString(initData)...)
return b
}
// encodeALiSOutput encodes an Output event (0x6F).
func encodeALiSOutput(id, relTimeMicros uint64, data string) []byte {
var b []byte
b = append(b, 0x6f)
b = append(b, encodeLEB128(id)...)
b = append(b, encodeLEB128(relTimeMicros)...)
b = append(b, encodeALiSString(data)...)
return b
}
// encodeALiSResize encodes a Resize event (0x72).
func encodeALiSResize(id, relTimeMicros, cols, rows uint64) []byte {
var b []byte
b = append(b, 0x72)
b = append(b, encodeLEB128(id)...)
b = append(b, encodeLEB128(relTimeMicros)...)
b = append(b, encodeLEB128(cols)...)
b = append(b, encodeLEB128(rows)...)
return b
}
// encodeALiSEOT encodes an EOT event (0x04).
func encodeALiSEOT(relTimeMicros uint64) []byte {
var b []byte
b = append(b, 0x04)
b = append(b, encodeLEB128(relTimeMicros)...)
return b
}
// ---------------------------------------------------------------------------
// ALiS v1 decoding (producer → server)
// ---------------------------------------------------------------------------
// decodeLEB128 decodes an unsigned LEB128 integer from the front of b.
// Returns the value and the remaining bytes. Panics if b is empty or malformed.
func decodeLEB128(b []byte) (uint64, []byte) {
var val uint64
var shift uint
for i, by := range b {
val |= uint64(by&0x7f) << shift
shift += 7
if by&0x80 == 0 {
return val, b[i+1:]
}
if shift >= 64 {
break
}
}
return 0, b
}
// decodeALiSString decodes a length-prefixed string from the front of b.
func decodeALiSString(b []byte) (string, []byte) {
length, rest := decodeLEB128(b)
if uint64(len(rest)) < length {
return "", rest
}
return string(rest[:length]), rest[length:]
}
// skipTheme skips the Theme field and returns remaining bytes.
func skipTheme(b []byte) []byte {
if len(b) == 0 {
return b
}
format := b[0]
b = b[1:]
switch format {
case 0x00:
// no theme
case 0x08:
// 8-color: fg(3) + bg(3) + 8×3 = 30 bytes
if len(b) >= 30 {
b = b[30:]
}
case 0x10:
// 16-color: fg(3) + bg(3) + 16×3 = 54 bytes
if len(b) >= 54 {
b = b[54:]
}
}
return b
}
// alisEvent is a parsed ALiS event from the producer.
type alisEvent struct {
kind string // "magic", "init", "output", "input", "resize", "marker", "exit", "eot"
// init
lastID uint64
time uint64 // absolute micros (init) or relative micros (others)
cols uint64
rows uint64
initData string
// output / input / marker
id uint64
data string
// exit
status uint64
}
// parseALiSMessage parses a single binary WebSocket message into an alisEvent.
func parseALiSMessage(msg []byte) (alisEvent, bool) {
if len(msg) == 0 {
return alisEvent{}, false
}
// Magic header check
if len(msg) == 5 && string(msg) == "ALiS\x01" {
return alisEvent{kind: "magic"}, true
}
evType := msg[0]
rest := msg[1:]
switch evType {
case 0x01: // Init
lastID, rest := decodeLEB128(rest)
timeMicros, rest := decodeLEB128(rest)
cols, rest := decodeLEB128(rest)
rows, rest := decodeLEB128(rest)
rest = skipTheme(rest)
initData, _ := decodeALiSString(rest)
return alisEvent{kind: "init", lastID: lastID, time: timeMicros, cols: cols, rows: rows, initData: initData}, true
case 0x6f: // Output
id, rest := decodeLEB128(rest)
relTime, rest := decodeLEB128(rest)
data, _ := decodeALiSString(rest)
return alisEvent{kind: "output", id: id, time: relTime, data: data}, true
case 0x69: // Input
id, rest := decodeLEB128(rest)
relTime, rest := decodeLEB128(rest)
data, _ := decodeALiSString(rest)
return alisEvent{kind: "input", id: id, time: relTime, data: data}, true
case 0x72: // Resize
id, rest := decodeLEB128(rest)
relTime, rest := decodeLEB128(rest)
cols, rest := decodeLEB128(rest)
rows, _ := decodeLEB128(rest)
return alisEvent{kind: "resize", id: id, time: relTime, cols: cols, rows: rows}, true
case 0x6d: // Marker
id, rest := decodeLEB128(rest)
relTime, rest := decodeLEB128(rest)
label, _ := decodeALiSString(rest)
return alisEvent{kind: "marker", id: id, time: relTime, data: label}, true
case 0x78: // Exit
id, rest := decodeLEB128(rest)
relTime, rest := decodeLEB128(rest)
status, _ := decodeLEB128(rest)
return alisEvent{kind: "exit", id: id, time: relTime, status: status}, true
case 0x04: // EOT
relTime, _ := decodeLEB128(rest)
return alisEvent{kind: "eot", time: relTime}, true
}
return alisEvent{}, false
}
// ---------------------------------------------------------------------------
// DB helpers for streams
// ---------------------------------------------------------------------------
type Stream struct {
ID int64
UserID int64
ProducerToken string
PublicToken string
Live bool
Ended bool
Title sql.NullString
Cols sql.NullInt64
Rows sql.NullInt64
}
func scanStream(row *sql.Row) (*Stream, error) {
s := &Stream{}
var live, ended int
err := row.Scan(&s.ID, &s.UserID, &s.ProducerToken, &s.PublicToken, &live, &ended, &s.Title, &s.Cols, &s.Rows)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
s.Live = live != 0
s.Ended = ended != 0
return s, nil
}
const streamSelectCols = `id, user_id, producer_token, public_token, live, ended, title, cols, rows`
func getStreamByProducerToken(db *sql.DB, token string) (*Stream, error) {
return scanStream(db.QueryRow(
`SELECT `+streamSelectCols+` FROM streams WHERE producer_token = ?`, token))
}
func getStreamByPublicToken(db *sql.DB, token string) (*Stream, error) {
return scanStream(db.QueryRow(
`SELECT `+streamSelectCols+` FROM streams WHERE public_token = ?`, token))
}
func getStreamByID(db *sql.DB, id int64, userID int64) (*Stream, error) {
return scanStream(db.QueryRow(
`SELECT `+streamSelectCols+` FROM streams WHERE id = ? AND user_id = ?`, id, userID))
}
// createStream inserts a new stream row and returns it.
func createStream(db *sql.DB, userID int64, title sql.NullString) (*Stream, error) {
pt := randomToken(20)
pubt := randomToken(20)
_, err := db.Exec(`
INSERT INTO streams (user_id, producer_token, public_token, live, ended, title)
VALUES (?, ?, ?, 1, 0, ?)`, userID, pt, pubt, title)
if err != nil {
return nil, err
}
return getStreamByProducerToken(db, pt)
}
func setStreamState(db *sql.DB, producerToken string, live, ended bool) {
l, e := 0, 0
if live {
l = 1
}
if ended {
e = 1
}
db.Exec(`UPDATE streams SET live = ?, ended = ?, updated_at = CURRENT_TIMESTAMP WHERE producer_token = ?`, l, e, producerToken)
}
func updateStreamSize(db *sql.DB, producerToken string, cols, rows int) {
db.Exec(`UPDATE streams SET cols = ?, rows = ?, updated_at = CURRENT_TIMESTAMP WHERE producer_token = ?`, cols, rows, producerToken)
}
// cleanupExpiredStreams deletes ended streams older than retentionDays and
// interrupted (offline, not ended) streams older than 30 days for a user.
// Chunks are deleted automatically via ON DELETE CASCADE.
func cleanupExpiredStreams(db *sql.DB, userID int64, retentionDays int) {
db.Exec(`
DELETE FROM streams WHERE user_id = ? AND (
(ended = 1 AND updated_at < datetime('now', '-' || ? || ' days'))
OR (ended = 0 AND live = 0 AND updated_at < datetime('now', '-30 days'))
)`, userID, retentionDays)
}
// deleteStream deletes a stream and its chunks (via ON DELETE CASCADE).
func deleteStream(db *sql.DB, streamID int64, userID int64) error {
_, err := db.Exec(`DELETE FROM streams WHERE id = ? AND user_id = ?`, streamID, userID)
return err
}
// StreamRow is used for listing a user's streams on the UI.
type StreamRow struct {
ID int64
PublicToken string
Title sql.NullString
Live bool
Ended bool
UpdatedAt time.Time
}
func listUserStreams(db *sql.DB, userID int64) ([]StreamRow, error) {
rows, err := db.Query(`
SELECT id, public_token, title, live, ended, updated_at
FROM streams WHERE user_id = ?
ORDER BY updated_at DESC`, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var result []StreamRow
for rows.Next() {
var s StreamRow
var live, ended int
if err := rows.Scan(&s.ID, &s.PublicToken, &s.Title, &live, &ended, &s.UpdatedAt); err != nil {
continue
}
s.Live = live != 0
s.Ended = ended != 0
result = append(result, s)
}
return result, nil
}
// timeAgo formats a time as a human-readable relative string.
func timeAgo(t time.Time) string {
d := time.Since(t)
switch {
case d < time.Minute:
return "just now"
case d < time.Hour:
m := int(d.Minutes())
if m == 1 {
return "1 minute ago"
}
return fmt.Sprintf("%d minutes ago", m)
case d < 24*time.Hour:
h := int(d.Hours())
if h == 1 {
return "1 hour ago"
}
return fmt.Sprintf("%d hours ago", h)
case d < 7*24*time.Hour:
days := int(d.Hours() / 24)
if days == 1 {
return "1 day ago"
}
return fmt.Sprintf("%d days ago", days)
default:
return t.Format("2006-01-02")
}
}
// streamJSON builds the API response map for a stream.
func streamJSON(s *Stream, baseURL string) map[string]any {
wsBase := baseURL
if len(wsBase) >= 5 && wsBase[:5] == "https" {
wsBase = "wss" + wsBase[5:]
} else if len(wsBase) >= 4 && wsBase[:4] == "http" {
wsBase = "ws" + wsBase[4:]
}
return map[string]any{
"id": s.ID,
"ws_producer_url": wsBase + "/ws/S/" + s.ProducerToken,
"url": baseURL + "/s/" + s.PublicToken,
}
}
// ---------------------------------------------------------------------------
// POST /api/v1/streams
// ---------------------------------------------------------------------------
func (s *Server) handleStreamCreate() http.Handler {
return s.requireCLI(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cli := cliFromRequest(r)
if cli.User == nil {
jsonError(w, "CLI not linked to account", http.StatusUnauthorized)
return
}
var params struct {
Live bool `json:"live"`
Title *string `json:"title"`
}
if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil {
jsonError(w, "Invalid JSON", http.StatusBadRequest)
return
}
if !params.Live {
jsonError(w, "live must be true", http.StatusBadRequest)
return
}
// Clean up expired streams for this user before creating a new one.
cleanupExpiredStreams(s.db, cli.User.ID, s.cfg.StreamRetentionDays)
var title sql.NullString
if params.Title != nil {
title = sql.NullString{String: *params.Title, Valid: true}
}
stream, err := createStream(s.db, cli.User.ID, title)
if err != nil {
jsonError(w, "DB error: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(streamJSON(stream, s.cfg.BaseURL))
}))
}
// ---------------------------------------------------------------------------
// PATCH /api/v1/streams/{id} — update stream (mark live, set metadata)
// ---------------------------------------------------------------------------
func (s *Server) handleStreamUpdate() http.Handler {
return s.requireCLI(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cli := cliFromRequest(r)
if cli.User == nil {
jsonError(w, "CLI not linked to account", http.StatusUnauthorized)
return
}
idStr := r.PathValue("id")
var streamID int64
fmt.Sscan(idStr, &streamID)
stream, err := getStreamByID(s.db, streamID, cli.User.ID)
if err != nil {
jsonError(w, "DB error", http.StatusInternalServerError)
return
}
if stream == nil {
jsonError(w, "Stream not found", http.StatusNotFound)
return
}
var params struct {
Live *bool `json:"live"`
Title *string `json:"title"`
}
json.NewDecoder(r.Body).Decode(¶ms)
if params.Title != nil {
s.db.Exec(`UPDATE streams SET title = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, *params.Title, streamID)
}
if params.Live != nil && *params.Live {
// Resuming: mark live=1, ended=0
s.db.Exec(`UPDATE streams SET live = 1, ended = 0, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, streamID)
}
// Re-fetch to return current state
stream, err = getStreamByID(s.db, streamID, cli.User.ID)
if err != nil || stream == nil {
jsonError(w, "DB error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(streamJSON(stream, s.cfg.BaseURL))
}))
}
// ---------------------------------------------------------------------------
// GET /api/v1/user/streams — list streams for current user
// ---------------------------------------------------------------------------
func (s *Server) handleUserStreamsList() http.Handler {
return s.requireCLI(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cli := cliFromRequest(r)
if cli.User == nil {
jsonError(w, "CLI not linked to account", http.StatusUnauthorized)
return
}
// "prefix" is the CLI's param name but we treat it as an exact match
// on public_token (the token visible in the stream URL /s/<token>).
publicToken := r.URL.Query().Get("prefix")
var result []map[string]any
if publicToken != "" {
stream, err := getStreamByPublicToken(s.db, publicToken)
if err != nil {
jsonError(w, "DB error", http.StatusInternalServerError)
return
}
if stream != nil && stream.UserID == cli.User.ID {
result = []map[string]any{streamJSON(stream, s.cfg.BaseURL)}
}
}
if result == nil {
result = []map[string]any{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(result)
}))
}
// ---------------------------------------------------------------------------
// POST /streams/{public_token}/delete — delete a stream (browser session auth)
// ---------------------------------------------------------------------------
func (s *Server) handleStreamBrowserDelete() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := s.sessionUser(r)
if err != nil || user == nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
publicToken := r.PathValue("public_token")
stream, err := getStreamByPublicToken(s.db, publicToken)
if err != nil || stream == nil {
http.NotFound(w, r)
return
}
if stream.UserID != user.ID {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
if err := deleteStream(s.db, stream.ID, user.ID); err != nil {
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/user/my-recordings", http.StatusSeeOther)
})
}
// ---------------------------------------------------------------------------
// POST /streams/{public_token}/rename — rename a stream (browser session auth)
// ---------------------------------------------------------------------------
func (s *Server) handleStreamBrowserRename() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := s.sessionUser(r)
if err != nil || user == nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
publicToken := r.PathValue("public_token")
stream, err := getStreamByPublicToken(s.db, publicToken)
if err != nil || stream == nil {
http.NotFound(w, r)
return
}
if stream.UserID != user.ID {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
r.ParseForm()
title := strings.TrimSpace(r.FormValue("title"))
s.db.Exec(`UPDATE streams SET title = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, title, stream.ID)
http.Redirect(w, r, "/user/my-recordings", http.StatusSeeOther)
})
}
// ---------------------------------------------------------------------------
// Producer WebSocket: GET /ws/S/{producer_token}
// ---------------------------------------------------------------------------
func (s *Server) handleProducerWS() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
producerToken := r.PathValue("producer_token")
// Verify stream exists, is marked live, and has not permanently ended.
stream, err := getStreamByProducerToken(s.db, producerToken)
if err != nil {
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
if stream == nil || !stream.Live || stream.Ended {
http.Error(w, "Stream not found", http.StatusNotFound)
return
}
// Register in hub (replacing any previous session)
ls := s.hub.put(producerToken, stream.PublicToken)
// Start recording goroutine — closed when producer disconnects.
recDone := make(chan struct{})
go runRecording(s.db, ls, stream.ID, recDone)
wsServer := websocket.Server{
Handshake: func(cfg *websocket.Config, r *http.Request) error {
cfg.Protocol = []string{"v1.alis"}
return nil
},
Handler: func(ws *websocket.Conn) {
ws.PayloadType = websocket.BinaryFrame
defer func() {
ls.mu.Lock()
wasEnded := ls.ended
if !wasEnded {
// Abrupt disconnect — stream offline but may resume.
if ls.vt != nil {
snap := ls.vt.Dump()
ls.endFrame = buildEndSnapshot(ls.lastEventID, ls.lastTimeMu, uint64(ls.cols), uint64(ls.rows), snap)
}
// Do NOT append EOT — consumers will close without EOT
// so the player shows "Stream offline" and retries.
}
ls.ended = true // stop consumer poll loops
ls.mu.Unlock()
// live=0, ended=0 for abrupt disconnect (may resume).
// live=0, ended=1 already set by EOT handler.
if !wasEnded {
setStreamState(s.db, producerToken, false, false)
}
s.hub.remove(producerToken, stream.PublicToken)
close(recDone)
log.Printf("producer/%s: disconnected (eot=%v)", producerToken, wasEnded)
}()
log.Printf("producer/%s: connected", producerToken)
gotMagic := false
for {
var msg []byte
if err := websocket.Message.Receive(ws, &msg); err != nil {
break
}
ev, ok := parseALiSMessage(msg)
if !ok {
log.Printf("producer/%s: unparseable message, ignoring", producerToken)
continue
}
switch ev.kind {
case "magic":
gotMagic = true
log.Printf("producer/%s: ALiS v1 magic received", producerToken)
case "init":
if !gotMagic {
log.Printf("producer/%s: init before magic, ignoring", producerToken)
continue
}
cols := int(ev.cols)
rows := int(ev.rows)
if cols <= 0 || rows <= 0 || cols > 720 || rows > 200 {
log.Printf("producer/%s: invalid size %dx%d", producerToken, cols, rows)
continue
}
initMsg := encodeALiSInit(ev.lastID, ev.time, ev.cols, ev.rows, ev.initData)
ls.mu.Lock()
ls.vt = avt.NewBuilder().Size(cols, rows).ScrollbackLimit(0).Build()
if ev.initData != "" {
ls.vt.FeedStr(ev.initData)
}
ls.cols = cols
ls.rows = rows
ls.lastEventID = ev.lastID
ls.startTime = time.Now()
ls.lastTimeMu = ev.time
ls.ended = false
ls.appendRing(initMsg)
ls.mu.Unlock()
go updateStreamSize(s.db, producerToken, cols, rows)
log.Printf("producer/%s: init %dx%d", producerToken, cols, rows)
case "output":
relTime := ev.time
outMsg := encodeALiSOutput(ev.id, relTime, ev.data)
ls.mu.Lock()
if ls.vt != nil {
ls.vt.FeedStr(ev.data)
}
ls.lastEventID = ev.id
ls.lastTimeMu += relTime
ls.appendRing(outMsg)
ls.mu.Unlock()
case "resize":
cols := int(ev.cols)
rows := int(ev.rows)
relTime := ev.time
resMsg := encodeALiSResize(ev.id, relTime, ev.cols, ev.rows)
ls.mu.Lock()
if ls.vt != nil {
ls.vt.Resize(cols, rows)
ls.cols = cols
ls.rows = rows
}
ls.lastEventID = ev.id
ls.lastTimeMu += relTime
ls.appendRing(resMsg)
ls.mu.Unlock()
go updateStreamSize(s.db, producerToken, cols, rows)
case "input", "marker", "exit":
ls.mu.Lock()
ls.lastEventID = ev.id
ls.lastTimeMu += ev.time
ls.appendRing(msg)
ls.mu.Unlock()
case "eot":
eotMsg := encodeALiSEOT(ev.time)
ls.mu.Lock()
ls.ended = true
ls.eotReceived = true
if ls.vt != nil {
snap := ls.vt.Dump()
ls.endFrame = buildEndSnapshot(ls.lastEventID, ls.lastTimeMu, uint64(ls.cols), uint64(ls.rows), snap)
}
ls.appendRing(eotMsg)
ls.mu.Unlock()
// Permanent end — live=0 ended=1.
setStreamState(s.db, producerToken, false, true)
log.Printf("producer/%s: EOT received, stream permanently ended", producerToken)
return
}
}
}}
wsServer.ServeHTTP(w, r)
})
}
// buildEndSnapshot constructs the Init message that late consumers get for an
// ended stream, encoding the final visible screen state.
func buildEndSnapshot(lastID, timeMicros, cols, rows uint64, dump string) []byte {
return encodeALiSInit(lastID, timeMicros, cols, rows, dump)
}
// runRecording runs flush (every 100ms) and compaction (every 10s) in a single
// goroutine. On shutdown (done closed): flush first, then compact — guaranteeing
// all events are written before the final snapshot is taken.
func runRecording(db *sql.DB, ls *LiveStream, streamID int64, done <-chan struct{}) {
flushTicker := time.NewTicker(100 * time.Millisecond)
compactTicker := time.NewTicker(10 * time.Second)
defer flushTicker.Stop()
defer compactTicker.Stop()
for {
select {
case <-flushTicker.C:
flushChunk(db, ls, streamID)
case <-compactTicker.C:
flushChunk(db, ls, streamID)
compactRecording(db, ls, streamID)
case <-done:
// Shutdown: flush first, then compact — order matters.
flushChunk(db, ls, streamID)
compactRecording(db, ls, streamID)
return
}
}
}
func flushChunk(db *sql.DB, ls *LiveStream, streamID int64) {
ls.mu.Lock()
buf := ls.recBuf
seqEnd := ls.lastRecSeq
ls.recBuf = new(bytes.Buffer)
ls.mu.Unlock()
if buf.Len() == 0 {
return
}
_, err := db.Exec(
`INSERT INTO stream_chunks (stream_id, chunk, seq_end) VALUES (?, ?, ?)`,
streamID, buf.Bytes(), seqEnd,
)
if err != nil {
log.Printf("stream %d: chunk flush error: %v", streamID, err)
}
}
func compactRecording(db *sql.DB, ls *LiveStream, streamID int64) {
ls.mu.Lock()
if ls.vt == nil {
ls.mu.Unlock()
return
}
snapshot := ls.vt.Dump()
seqID := ls.lastEventID
timeMicros := ls.lastTimeMu
ls.mu.Unlock()
_, err := db.Exec(`
UPDATE streams SET
snapshot = ?,
snapshot_seq = ?,
snapshot_time = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?`, snapshot, seqID, timeMicros, streamID)
if err != nil {
log.Printf("stream %d: snapshot update error: %v", streamID, err)
return
}
_, err = db.Exec(
`DELETE FROM stream_chunks WHERE stream_id = ? AND seq_end <= ?`,
streamID, seqID,
)
if err != nil {
log.Printf("stream %d: chunk compaction error: %v", streamID, err)
}
}
// ---------------------------------------------------------------------------
// Consumer WebSocket: GET /ws/s/{public_token}
// ---------------------------------------------------------------------------
func (s *Server) handleConsumerWS() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
publicToken := r.PathValue("public_token")
// Check DB first — stream must exist.
dbStream, err := getStreamByPublicToken(s.db, publicToken)
if err != nil || dbStream == nil {
http.Error(w, "Stream not found", http.StatusNotFound)
return
}
// Try hub for an active session.
ls := s.hub.getByPublic(publicToken)
wsServer := websocket.Server{
Handshake: func(cfg *websocket.Config, r *http.Request) error {
cfg.Protocol = []string{"v1.alis"}
return nil
},
Handler: func(ws *websocket.Conn) {
ws.PayloadType = websocket.BinaryFrame
if err := websocket.Message.Send(ws, encodeALiSMagic()); err != nil {
return
}
if ls == nil {
// No active session in hub.
if dbStream.Ended {
// Permanently ended — send snapshot (if available) then EOT
// so the player shows the last screen state and "Stream ended".
var snapshot sql.NullString
var snapshotSeq, snapshotTime sql.NullInt64
s.db.QueryRow(`SELECT snapshot, snapshot_seq, snapshot_time FROM streams WHERE id = ?`, dbStream.ID).
Scan(&snapshot, &snapshotSeq, &snapshotTime)
if snapshot.Valid && snapshot.String != "" && dbStream.Cols.Valid && dbStream.Rows.Valid {
initMsg := encodeALiSInit(
uint64(snapshotSeq.Int64),
uint64(snapshotTime.Int64),
uint64(dbStream.Cols.Int64),
uint64(dbStream.Rows.Int64),
snapshot.String,
)
websocket.Message.Send(ws, initMsg)
}
websocket.Message.Send(ws, encodeALiSEOT(0))
}
// Otherwise offline but may resume — close without EOT,
// player shows "Stream offline" and retries.
return
}
// Active session — snapshot current VT state.
ls.mu.Lock()
var initMsg []byte
var lastSeqID uint64
if ls.vt != nil {
dump := ls.vt.Dump()
initMsg = encodeALiSInit(
ls.lastEventID, ls.lastTimeMu,
uint64(ls.cols), uint64(ls.rows),
dump,
)
lastSeqID = ls.seqID
}
ls.mu.Unlock()
// If producer hasn't sent Init yet, poll until it does.
if initMsg == nil {
waitTicker := time.NewTicker(5 * time.Millisecond)
defer waitTicker.Stop()
for range waitTicker.C {
ls.mu.Lock()
if ls.vt != nil {
dump := ls.vt.Dump()
initMsg = encodeALiSInit(
ls.lastEventID, ls.lastTimeMu,
uint64(ls.cols), uint64(ls.rows),
dump,
)
lastSeqID = ls.seqID
}
done := ls.ended
ls.mu.Unlock()
if initMsg != nil || done {
break
}
}
}
if initMsg != nil {
if err := websocket.Message.Send(ws, initMsg); err != nil {
return
}
}
// Poll ring buffer every 5ms.
ticker := time.NewTicker(5 * time.Millisecond)
defer ticker.Stop()
for range ticker.C {
ls.mu.Lock()
msgs, currentSeqID := ls.readRing(lastSeqID)
done := ls.ended
eot := ls.eotReceived
ls.mu.Unlock()
for _, msg := range msgs {
if err := websocket.Message.Send(ws, msg); err != nil {
return
}
}
lastSeqID = currentSeqID
if done && len(msgs) == 0 {
if !eot {
// Abrupt disconnect — close without EOT,
// player shows "Stream offline" and retries.
}
// EOT case: EOT message already in ring buffer and
// sent above — player shows "Stream ended".
return
}
}
}}
wsServer.ServeHTTP(w, r)
})
}
// ---------------------------------------------------------------------------
// Live stream PNG snapshot: GET /s/{public_token}/current.png
// ---------------------------------------------------------------------------
func (s *Server) handleLiveStreamPreviewPNG() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
publicToken := r.PathValue("public_token")
ls := s.hub.getByPublic(publicToken)
if ls == nil {
http.NotFound(w, r)
return
}
ls.mu.Lock()
if ls.vt == nil || ls.cols == 0 {
ls.mu.Unlock()
http.Error(w, "Stream not yet initialised", http.StatusServiceUnavailable)
return
}
lines := ls.vt.View()
ls.mu.Unlock()
// Resolve theme via owner's DB preference
stream, _ := getStreamByPublicToken(s.db, publicToken)
var userID int64
if stream != nil {
userID = stream.UserID
}
darkID, _ := resolveEmbedThemes(r, s.db, sql.NullInt64{Int64: userID, Valid: userID != 0})
theme := themesByID[darkID]
img := renderStreamPreviewPNG(lines, theme)
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
http.Error(w, "render error", http.StatusInternalServerError)
return
}
data := buf.Bytes()
etag := fmt.Sprintf(`"%x"`, md5.Sum(data))
w.Header().Set("ETag", etag)
w.Header().Set("Cache-Control", "no-cache")
if r.Header.Get("If-None-Match") == etag {
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set("Content-Type", "image/png")
w.Write(data)
})
}
// ---------------------------------------------------------------------------
// Live player page: GET /s/{public_token}
// ---------------------------------------------------------------------------
func (s *Server) handleLiveStreamShow() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
publicToken := r.PathValue("public_token")
stream, err := getStreamByPublicToken(s.db, publicToken)
if err != nil {
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
if stream == nil {
http.NotFound(w, r)
return
}
// Build consumer WS URL
wsBase := s.cfg.BaseURL
if len(wsBase) >= 5 && wsBase[:5] == "https" {
wsBase = "wss" + wsBase[5:]
} else if len(wsBase) >= 4 && wsBase[:4] == "http" {
wsBase = "ws" + wsBase[4:]
}
wsURL := wsBase + "/ws/s/" + publicToken
wsURLJSON, _ := json.Marshal(wsURL)
cols, rows := 0, 0
if stream.Cols.Valid {
cols = int(stream.Cols.Int64)
}
if stream.Rows.Valid {
rows = int(stream.Rows.Int64)
}
title := "live stream"
if stream.Title.Valid && stream.Title.String != "" {
title = stream.Title.String
}
pt := resolveTheme(r)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
playerTmpl.Execute(w, playerData{
pageTheme: pt,
Title: title,
AppTitle: s.cfg.AppTitle,
CastURL: wsURL,
CastSrc: template.JS(wsURLJSON),
TermCols: cols,
TermRows: rows,
LiveStream: true,
UpstreamPlayer: r.URL.Query().Get("player") == "upstream",
})
})
}
|