-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge_test.go
More file actions
2152 lines (1840 loc) · 63.1 KB
/
bridge_test.go
File metadata and controls
2152 lines (1840 loc) · 63.1 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
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
package main
import (
"crypto/ed25519"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
// ---------- Test Helpers ----------
// testBridgeRegistry creates a registry in a temp dir with one public channel.
func testBridgeRegistry(t *testing.T) *bridgeRegistry {
t.Helper()
dir := t.TempDir()
r := newBridgeRegistry(dir, "")
channels := []bridgeChannel{{
ID: "ch1",
Name: "Test Channel",
Stream: "http://upstream.example.com/live/stream.m3u8",
Tags: []string{"test"},
Language: "en",
}}
if err := r.UpdateChannels(channels); err != nil {
t.Fatal(err)
}
return r
}
// testBridgeChannelID returns the TLTV channel ID for "ch1" in the registry.
func testBridgeChannelID(t *testing.T, r *bridgeRegistry) string {
t.Helper()
channels := r.ListChannels()
if len(channels) == 0 {
t.Fatal("no channels registered")
}
return channels[0].ChannelID
}
// ---------- M3U Parsing ----------
func TestBridgeParseM3U_FullAttributes(t *testing.T) {
m3u := `#EXTM3U
#EXTINF:-1 tvg-id="ch1" tvg-name="Channel One" tvg-logo="http://logo.png" group-title="News",Channel One
http://example.com/ch1/stream.m3u8
#EXTINF:-1 tvg-id="ch2" tvg-name="Channel Two" group-title="Sports",Channel Two
http://example.com/ch2/stream.m3u8
`
channels := bridgeParseM3U(m3u, "http://provider.com/playlist.m3u")
if len(channels) != 2 {
t.Fatalf("expected 2 channels, got %d", len(channels))
}
ch := channels[0]
if ch.ID != "ch1" {
t.Errorf("ch1 ID = %q, want %q", ch.ID, "ch1")
}
if ch.Name != "Channel One" {
t.Errorf("ch1 Name = %q, want %q", ch.Name, "Channel One")
}
if ch.Logo != "http://logo.png" {
t.Errorf("ch1 Logo = %q, want %q", ch.Logo, "http://logo.png")
}
if len(ch.Tags) != 1 || ch.Tags[0] != "News" {
t.Errorf("ch1 Tags = %v, want [News]", ch.Tags)
}
if ch.Stream != "http://example.com/ch1/stream.m3u8" {
t.Errorf("ch1 Stream = %q, want absolute URL", ch.Stream)
}
if channels[1].ID != "ch2" {
t.Errorf("ch2 ID = %q, want %q", channels[1].ID, "ch2")
}
}
func TestBridgeParseM3U_BareEXTINF(t *testing.T) {
m3u := `#EXTM3U
#EXTINF:-1,My Channel
http://example.com/stream.m3u8
`
channels := bridgeParseM3U(m3u, "")
if len(channels) != 1 {
t.Fatalf("expected 1 channel, got %d", len(channels))
}
if channels[0].Name != "My Channel" {
t.Errorf("Name = %q, want %q", channels[0].Name, "My Channel")
}
if channels[0].ID != "My_Channel" {
t.Errorf("ID = %q, want sanitized name", channels[0].ID)
}
}
func TestBridgeParseM3U_MissingTvgId(t *testing.T) {
m3u := `#EXTM3U
#EXTINF:-1 tvg-name="Test",Test
http://example.com/stream.m3u8
`
channels := bridgeParseM3U(m3u, "")
if len(channels) != 1 {
t.Fatalf("expected 1 channel, got %d", len(channels))
}
// ID should be generated from name
if channels[0].ID != "Test" {
t.Errorf("ID = %q, want sanitized name %q", channels[0].ID, "Test")
}
}
// ---------- XMLTV Parsing ----------
func TestBridgeParseXMLTVGuide(t *testing.T) {
xmltv := `<?xml version="1.0" encoding="UTF-8"?>
<tv>
<channel id="ch1">
<display-name>Channel One</display-name>
</channel>
<programme start="20260315120000 +0000" stop="20260315130000 +0000" channel="ch1">
<title>News Hour</title>
<desc>Daily news</desc>
<category>news</category>
</programme>
<programme start="20260315130000 +0000" stop="20260315140000 +0000" channel="ch1">
<title>Sports</title>
</programme>
</tv>`
guide, err := bridgeParseXMLTVGuide([]byte(xmltv))
if err != nil {
t.Fatal(err)
}
entries, ok := guide["ch1"]
if !ok {
t.Fatal("no entries for ch1")
}
if len(entries) != 2 {
t.Fatalf("expected 2 entries, got %d", len(entries))
}
if entries[0].Start != "2026-03-15T12:00:00Z" {
t.Errorf("entry 0 Start = %q, want %q", entries[0].Start, "2026-03-15T12:00:00Z")
}
if entries[0].End != "2026-03-15T13:00:00Z" {
t.Errorf("entry 0 End = %q, want %q", entries[0].End, "2026-03-15T13:00:00Z")
}
if entries[0].Title != "News Hour" {
t.Errorf("entry 0 Title = %q, want %q", entries[0].Title, "News Hour")
}
if entries[0].Description != "Daily news" {
t.Errorf("entry 0 Description = %q", entries[0].Description)
}
if entries[0].Category != "news" {
t.Errorf("entry 0 Category = %q", entries[0].Category)
}
}
func TestBridgeXMLTVToISO(t *testing.T) {
tests := []struct {
in, want string
}{
{"20260315120000 +0000", "2026-03-15T12:00:00Z"},
{"20260101000000 +0000", "2026-01-01T00:00:00Z"},
{"20261231235959 +0000", "2026-12-31T23:59:59Z"},
{"20260315120000 +0500", "2026-03-15T07:00:00Z"}, // timezone offset
}
for _, tt := range tests {
got, err := bridgeXMLTVToISO(tt.in)
if err != nil {
t.Errorf("bridgeXMLTVToISO(%q) error: %v", tt.in, err)
continue
}
if got != tt.want {
t.Errorf("bridgeXMLTVToISO(%q) = %q, want %q", tt.in, got, tt.want)
}
}
}
func TestBridgeISOToXMLTV(t *testing.T) {
tests := []struct {
in, want string
}{
{"2026-03-15T12:00:00Z", "20260315120000 +0000"},
{"2026-01-01T00:00:00Z", "20260101000000 +0000"},
}
for _, tt := range tests {
got := isoToXMLTV(tt.in)
if got != tt.want {
t.Errorf("isoToXMLTV(%q) = %q, want %q", tt.in, got, tt.want)
}
}
}
// ---------- JSON Parsing ----------
func TestBridgeParseJSONChannels(t *testing.T) {
data := `[
{"id": "ch1", "name": "Channel One", "stream": "http://example.com/ch1.m3u8"},
{"id": "ch2", "name": "Channel Two", "stream": "http://example.com/ch2.m3u8", "access": "token", "token": "secret"}
]`
channels, err := bridgeParseJSONChannels([]byte(data))
if err != nil {
t.Fatal(err)
}
if len(channels) != 2 {
t.Fatalf("expected 2 channels, got %d", len(channels))
}
if channels[0].Name != "Channel One" {
t.Errorf("ch0 Name = %q", channels[0].Name)
}
if channels[1].Access != "token" || channels[1].Token != "secret" {
t.Errorf("ch1 Access=%q Token=%q", channels[1].Access, channels[1].Token)
}
}
func TestBridgeParseJSONGuide(t *testing.T) {
data := `[
{"channel": "ch1", "start": "2026-03-15T12:00:00Z", "end": "2026-03-15T13:00:00Z", "title": "Show A"},
{"channel": "ch1", "start": "2026-03-15T13:00:00Z", "end": "2026-03-15T14:00:00Z", "title": "Show B"},
{"channel": "ch2", "start": "2026-03-15T12:00:00Z", "end": "2026-03-15T13:00:00Z", "title": "Show C"}
]`
guide, err := bridgeParseJSONGuide([]byte(data))
if err != nil {
t.Fatal(err)
}
if len(guide["ch1"]) != 2 {
t.Errorf("ch1 entries: %d, want 2", len(guide["ch1"]))
}
if len(guide["ch2"]) != 1 {
t.Errorf("ch2 entries: %d, want 1", len(guide["ch2"]))
}
}
// ---------- Source Auto-Detection ----------
func TestBridgeIsM3UPlaylist(t *testing.T) {
// IPTV M3U
if !bridgeIsM3UPlaylist("#EXTM3U\n#EXTINF:-1,Channel\nhttp://example.com/stream.m3u8\n") {
t.Error("should detect IPTV M3U as M3U playlist")
}
// HLS media playlist (has TARGETDURATION)
if bridgeIsM3UPlaylist("#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6.0,\nseg-001.ts\n") {
t.Error("should NOT detect HLS media playlist as M3U playlist")
}
// HLS master playlist (has STREAM-INF)
if bridgeIsM3UPlaylist("#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=2000000\nvideo.m3u8\n") {
t.Error("should NOT detect HLS master playlist as M3U playlist")
}
// No EXTINF at all
if bridgeIsM3UPlaylist("just some text content") {
t.Error("should NOT detect plain text as M3U playlist")
}
}
// ---------- Directory Scanning ----------
func TestBridgeScanDirectory(t *testing.T) {
dir := t.TempDir()
// Create a .m3u8 file
os.WriteFile(filepath.Join(dir, "test-channel.m3u8"), []byte("#EXTM3U\n#EXTINF:2.0,\nseg.ts\n"), 0644)
// Create a sidecar JSON
sidecar := `{"name": "Test Channel", "description": "A test", "tags": ["demo"], "guide": [{"start": "2026-03-31T00:00:00Z", "end": "2026-04-01T00:00:00Z", "title": "Color Bars"}]}`
os.WriteFile(filepath.Join(dir, "test-channel.json"), []byte(sidecar), 0644)
// Create another .m3u8 without sidecar
os.WriteFile(filepath.Join(dir, "bare.m3u8"), []byte("#EXTM3U\n"), 0644)
channels, guide, err := bridgeScanDirectory(dir)
if err != nil {
t.Fatal(err)
}
if len(channels) != 2 {
t.Fatalf("expected 2 channels, got %d", len(channels))
}
// Find the test-channel
var testCh *bridgeChannel
for i := range channels {
if channels[i].ID == "test-channel" {
testCh = &channels[i]
}
}
if testCh == nil {
t.Fatal("test-channel not found")
}
if testCh.Name != "Test Channel" {
t.Errorf("Name = %q, want %q", testCh.Name, "Test Channel")
}
if testCh.Description != "A test" {
t.Errorf("Description = %q", testCh.Description)
}
if len(testCh.Tags) != 1 || testCh.Tags[0] != "demo" {
t.Errorf("Tags = %v", testCh.Tags)
}
// Check guide from sidecar
if entries, ok := guide["test-channel"]; !ok || len(entries) != 1 {
t.Errorf("guide entries for test-channel: %v", guide["test-channel"])
} else if entries[0].Title != "Color Bars" {
t.Errorf("guide entry title = %q", entries[0].Title)
}
}
// ---------- HLS Manifest Rewriting ----------
func TestBridgeRewriteManifest_AbsoluteToRelative(t *testing.T) {
manifest := "#EXTM3U\n#EXTINF:2.0,\nhttp://upstream.example.com/live/seg-001.ts\n#EXTINF:2.0,\nhttp://upstream.example.com/live/seg-002.ts\n"
result := string(rewriteManifest("http://upstream.example.com/live/stream.m3u8", []byte(manifest), ""))
if strings.Contains(result, "http://") {
t.Error("result still contains absolute URLs")
}
if !strings.Contains(result, "seg-001.ts") {
t.Error("missing seg-001.ts")
}
if !strings.Contains(result, "seg-002.ts") {
t.Error("missing seg-002.ts")
}
}
func TestBridgeRewriteManifest_RelativePassThrough(t *testing.T) {
manifest := "#EXTM3U\n#EXTINF:2.0,\nseg-001.ts\n"
result := string(rewriteManifest("http://upstream.example.com/live/stream.m3u8", []byte(manifest), ""))
if !strings.Contains(result, "seg-001.ts") {
t.Error("relative URI should pass through")
}
}
func TestBridgeRewriteManifest_DifferentOriginLeftAbsolute(t *testing.T) {
manifest := "#EXTM3U\n#EXTINF:2.0,\nhttp://cdn.other.com/seg-001.ts\n"
result := string(rewriteManifest("http://upstream.example.com/live/stream.m3u8", []byte(manifest), ""))
if !strings.Contains(result, "http://cdn.other.com/seg-001.ts") {
t.Error("different-origin URL should be left absolute")
}
}
func TestBridgeRewriteManifest_TokenInjection(t *testing.T) {
manifest := "#EXTM3U\n#EXTINF:2.0,\nseg-001.ts\n#EXTINF:2.0,\nseg-002.ts\n"
result := string(rewriteManifest("", []byte(manifest), "secret123"))
if !strings.Contains(result, "seg-001.ts?token=secret123") {
t.Error("missing token on seg-001.ts")
}
if !strings.Contains(result, "seg-002.ts?token=secret123") {
t.Error("missing token on seg-002.ts")
}
}
func TestBridgeRewriteManifest_TokenOnAbsoluteRewritten(t *testing.T) {
manifest := "#EXTM3U\n#EXTINF:2.0,\nhttp://upstream.example.com/live/seg-001.ts\n"
result := string(rewriteManifest("http://upstream.example.com/live/stream.m3u8", []byte(manifest), "tok"))
if strings.Contains(result, "http://") {
t.Error("should be rewritten to relative")
}
if !strings.Contains(result, "seg-001.ts?token=tok") {
t.Error("should have token appended")
}
}
func TestBridgeRewriteManifest_NoTokenForPublic(t *testing.T) {
manifest := "#EXTM3U\n#EXTINF:2.0,\nseg-001.ts\n"
result := string(rewriteManifest("", []byte(manifest), ""))
if strings.Contains(result, "token=") {
t.Error("public channels should have no token")
}
}
func TestBridgeRewriteManifest_MapURI(t *testing.T) {
manifest := "#EXTM3U\n#EXT-X-MAP:URI=\"http://upstream.example.com/live/init.mp4\"\n#EXTINF:2.0,\nseg.ts\n"
result := string(rewriteManifest("http://upstream.example.com/live/stream.m3u8", []byte(manifest), ""))
if !strings.Contains(result, `URI="init.mp4"`) {
t.Errorf("MAP URI not rewritten to relative: %s", result)
}
}
func TestBridgeRewriteManifest_KeyURI(t *testing.T) {
manifest := "#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"http://upstream.example.com/live/key.bin\"\n"
result := string(rewriteManifest("http://upstream.example.com/live/stream.m3u8", []byte(manifest), ""))
if !strings.Contains(result, `URI="key.bin"`) {
t.Errorf("KEY URI not rewritten: %s", result)
}
}
func TestBridgeRewriteManifest_MediaURI(t *testing.T) {
manifest := "#EXTM3U\n#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"audio\",URI=\"http://upstream.example.com/live/audio.m3u8\"\n"
result := string(rewriteManifest("http://upstream.example.com/live/stream.m3u8", []byte(manifest), ""))
if !strings.Contains(result, `URI="audio.m3u8"`) {
t.Errorf("MEDIA URI not rewritten: %s", result)
}
}
func TestBridgeRewriteManifest_TagURIWithToken(t *testing.T) {
manifest := "#EXTM3U\n" +
"#EXT-X-MAP:URI=\"init.mp4\"\n" +
"#EXT-X-KEY:METHOD=AES-128,URI=\"key.bin\",IV=0x1234\n" +
"#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"audio\",URI=\"audio.m3u8\"\n" +
"#EXTINF:2.0,\nseg-001.ts\n"
result := string(rewriteManifest("", []byte(manifest), "secret"))
if !strings.Contains(result, `URI="init.mp4?token=secret"`) {
t.Errorf("MAP URI missing token: %s", result)
}
if !strings.Contains(result, `URI="key.bin?token=secret"`) {
t.Errorf("KEY URI missing token: %s", result)
}
if !strings.Contains(result, `URI="audio.m3u8?token=secret"`) {
t.Errorf("MEDIA URI missing token: %s", result)
}
if !strings.Contains(result, "seg-001.ts?token=secret") {
t.Errorf("segment missing token: %s", result)
}
}
func TestBridgeRewriteManifest_NonURITagsUntouched(t *testing.T) {
manifest := "#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:2\n#EXT-X-MEDIA-SEQUENCE:42\n#EXTINF:2.0,\nseg.ts\n"
result := string(rewriteManifest("", []byte(manifest), "tok"))
if !strings.Contains(result, "#EXT-X-VERSION:3") {
t.Error("VERSION tag modified")
}
if !strings.Contains(result, "#EXT-X-TARGETDURATION:2") {
t.Error("TARGETDURATION tag modified")
}
if !strings.Contains(result, "#EXT-X-MEDIA-SEQUENCE:42") {
t.Error("MEDIA-SEQUENCE tag modified")
}
}
func TestBridgeRewriteManifest_UpstreamQueryStripped(t *testing.T) {
manifest := "#EXTM3U\n#EXTINF:2.0,\nhttp://upstream.example.com/live/seg-001.ts\n"
result := string(rewriteManifest("http://upstream.example.com/live/stream.m3u8?key=abc&auth=xyz", []byte(manifest), ""))
if strings.Contains(result, "http://") {
t.Error("should still rewrite to relative even with query on manifest URL")
}
if !strings.Contains(result, "seg-001.ts") {
t.Error("missing segment")
}
}
func TestBridgeRewriteManifest_TokenOnVariantPlaylist(t *testing.T) {
manifest := "#EXTM3U\n" +
"#EXT-X-STREAM-INF:BANDWIDTH=2000000,RESOLUTION=1280x720\n" +
"video-720p.m3u8\n" +
"#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360\n" +
"video-360p.m3u8\n"
result := string(rewriteManifest("", []byte(manifest), "tok"))
if !strings.Contains(result, "video-720p.m3u8?token=tok") {
t.Error("variant 720p missing token")
}
if !strings.Contains(result, "video-360p.m3u8?token=tok") {
t.Error("variant 360p missing token")
}
}
func TestBridgeRewriteManifest_FullPrivateScenario(t *testing.T) {
manifest := "#EXTM3U\n" +
"#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"audio\",URI=\"http://upstream.example.com/live/audio.m3u8\"\n" +
"#EXT-X-STREAM-INF:BANDWIDTH=2000000\n" +
"http://upstream.example.com/live/video.m3u8\n" +
"#EXT-X-STREAM-INF:BANDWIDTH=800000\n" +
"http://upstream.example.com/live/video-low.m3u8\n"
result := string(rewriteManifest("http://upstream.example.com/live/master.m3u8", []byte(manifest), "mytoken"))
if strings.Contains(result, "http://") {
t.Error("all absolute URLs should be rewritten to relative")
}
if !strings.Contains(result, `URI="audio.m3u8?token=mytoken"`) {
t.Error("audio URI missing token")
}
if !strings.Contains(result, "video.m3u8?token=mytoken") {
t.Error("video URI missing token")
}
if !strings.Contains(result, "video-low.m3u8?token=mytoken") {
t.Error("video-low URI missing token")
}
}
func TestBridgeRewriteManifest_FullPrivateMediaPlaylist(t *testing.T) {
manifest := "#EXTM3U\n" +
"#EXT-X-TARGETDURATION:2\n" +
"#EXT-X-MEDIA-SEQUENCE:100\n" +
"#EXT-X-MAP:URI=\"init.mp4\"\n" +
"#EXT-X-KEY:METHOD=AES-128,URI=\"key.bin\",IV=0x1234\n" +
"#EXTINF:2.0,\nseg-100.m4s\n" +
"#EXTINF:2.0,\nseg-101.m4s\n" +
"#EXTINF:2.0,\nseg-102.m4s\n"
result := string(rewriteManifest("", []byte(manifest), "tok"))
if !strings.Contains(result, `URI="init.mp4?token=tok"`) {
t.Error("MAP URI missing token")
}
if !strings.Contains(result, `URI="key.bin?token=tok"`) {
t.Error("KEY URI missing token")
}
for _, seg := range []string{"seg-100.m4s", "seg-101.m4s", "seg-102.m4s"} {
if !strings.Contains(result, seg+"?token=tok") {
t.Errorf("segment %s missing token", seg)
}
}
// Non-URI tags preserved
if !strings.Contains(result, "#EXT-X-TARGETDURATION:2") {
t.Error("TARGETDURATION modified")
}
if !strings.Contains(result, "#EXT-X-MEDIA-SEQUENCE:100") {
t.Error("MEDIA-SEQUENCE modified")
}
if !strings.Contains(result, "IV=0x1234") {
t.Error("KEY IV not preserved")
}
}
// ---------- Token Helpers ----------
func TestBridgeAppendToken_NoExistingQuery(t *testing.T) {
got := bridgeAppendToken("seg-001.ts", "abc")
if got != "seg-001.ts?token=abc" {
t.Errorf("got %q", got)
}
}
func TestBridgeAppendToken_ExistingQuery(t *testing.T) {
got := bridgeAppendToken("seg-001.ts?quality=high", "abc")
if got != "seg-001.ts?quality=high&token=abc" {
t.Errorf("got %q", got)
}
}
func TestBridgeMakeRelative_SameBase(t *testing.T) {
got := bridgeMakeRelative("http://example.com/live/seg-001.ts", "http://example.com/live/")
if got != "seg-001.ts" {
t.Errorf("got %q", got)
}
}
func TestBridgeMakeRelative_DifferentBase(t *testing.T) {
got := bridgeMakeRelative("http://cdn.other.com/seg-001.ts", "http://example.com/live/")
if got != "http://cdn.other.com/seg-001.ts" {
t.Errorf("got %q, should be unchanged", got)
}
}
func TestBridgeMakeRelative_AlreadyRelative(t *testing.T) {
got := bridgeMakeRelative("seg-001.ts", "http://example.com/live/")
if got != "seg-001.ts" {
t.Errorf("got %q, should be unchanged", got)
}
}
// ---------- Protocol Endpoints ----------
func TestBridgeNodeInfo(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
req := httptest.NewRequest("GET", "/.well-known/tltv", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("status = %d, want 200", w.Code)
}
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
if resp["protocol"] != "tltv" {
t.Errorf("protocol = %v", resp["protocol"])
}
channels, ok := resp["channels"].([]interface{})
if !ok || len(channels) != 1 {
t.Fatalf("expected 1 channel, got %v", resp["channels"])
}
ch := channels[0].(map[string]interface{})
if ch["name"] != "Test Channel" {
t.Errorf("channel name = %v", ch["name"])
}
id, _ := ch["id"].(string)
if !strings.HasPrefix(id, "TV") {
t.Errorf("channel ID should start with TV, got %q", id)
}
}
func TestBridgeChannelMetadata(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
id := testBridgeChannelID(t, r)
req := httptest.NewRequest("GET", "/tltv/v1/channels/"+id, nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("status = %d, want 200", w.Code)
}
ct := w.Header().Get("Content-Type")
if !strings.Contains(ct, "application/json") {
t.Errorf("Content-Type = %q", ct)
}
var doc map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &doc)
if doc["name"] != "Test Channel" {
t.Errorf("name = %v", doc["name"])
}
if doc["id"] != id {
t.Errorf("id = %v, want %s", doc["id"], id)
}
if _, ok := doc["signature"]; !ok {
t.Error("missing signature field")
}
// Verify signature
pubKey, err := parseChannelID(id)
if err != nil {
t.Fatal(err)
}
sigStr, _ := doc["signature"].(string)
sigBytes, err := b58Decode(sigStr)
if err != nil {
t.Fatal(err)
}
// Remove signature for verification
delete(doc, "signature")
payload, err := canonicalJSON(doc)
if err != nil {
t.Fatal(err)
}
if !ed25519.Verify(pubKey, payload, sigBytes) {
t.Error("signature verification failed")
}
}
func TestBridgeChannelMetadata_HasGuide(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
id := testBridgeChannelID(t, r)
req := httptest.NewRequest("GET", "/tltv/v1/channels/"+id, nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
var doc map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &doc)
guide, ok := doc["guide"].(string)
if !ok || guide == "" {
t.Error("metadata should have non-empty guide field")
}
}
func TestBridgeDefaultGuide(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
id := testBridgeChannelID(t, r)
req := httptest.NewRequest("GET", "/tltv/v1/channels/"+id+"/guide.json", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("status = %d, want 200", w.Code)
}
var doc map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &doc)
if _, ok := doc["signature"]; !ok {
t.Error("guide should have signature")
}
entries, ok := doc["entries"].([]interface{})
if !ok || len(entries) == 0 {
t.Fatal("guide should have entries")
}
entry := entries[0].(map[string]interface{})
if entry["title"] != "Test Channel" {
t.Errorf("default guide entry title = %v, want channel name", entry["title"])
}
}
func TestBridgeGuideXML(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
id := testBridgeChannelID(t, r)
req := httptest.NewRequest("GET", "/tltv/v1/channels/"+id+"/guide.xml", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("status = %d, want 200", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "<tv>") {
t.Error("missing <tv> tag")
}
if !strings.Contains(body, "Test Channel") {
t.Error("missing channel name in XMLTV")
}
ct := w.Header().Get("Content-Type")
if !strings.Contains(ct, "application/xml") {
t.Errorf("Content-Type = %q", ct)
}
}
func TestBridgeChannelNotFound(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
req := httptest.NewRequest("GET", "/tltv/v1/channels/TVfakeChannelIdThatDoesNotExistInRegistryXXXXX", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != 404 {
t.Fatalf("status = %d, want 404", w.Code)
}
}
func TestBridgePeers_Empty(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
req := httptest.NewRequest("GET", "/tltv/v1/peers", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("status = %d, want 200", w.Code)
}
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
peers, _ := resp["peers"].([]interface{})
if len(peers) != 0 {
t.Errorf("expected empty peers, got %d", len(peers))
}
}
func TestBridgePeers_WithConfigured(t *testing.T) {
dir := t.TempDir()
r := newBridgeRegistry(dir, "bridge.example.com:8000")
r.UpdateChannels([]bridgeChannel{{ID: "ch1", Name: "Test", Stream: "http://example.com/stream.m3u8"}})
srv := newBridgeServer(r, nil, nil, nil)
req := httptest.NewRequest("GET", "/tltv/v1/peers", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
peers, _ := resp["peers"].([]interface{})
// Own channels no longer appear in peers (visible via /.well-known/tltv instead)
if len(peers) != 0 {
t.Fatalf("expected 0 peers (own channels excluded), got %d", len(peers))
}
}
func TestBridgeHealth(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
req := httptest.NewRequest("GET", "/health", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("status = %d, want 200", w.Code)
}
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
if resp["status"] != "ok" {
t.Errorf("status = %v, want ok", resp["status"])
}
if resp["version"] != version {
t.Errorf("version = %v, want %s", resp["version"], version)
}
if resp["channels"] != float64(1) {
t.Errorf("channels = %v, want 1", resp["channels"])
}
}
func TestBridgeCORSHeaders(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
req := httptest.NewRequest("GET", "/.well-known/tltv", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Header().Get("Access-Control-Allow-Origin") != "*" {
t.Error("missing CORS header")
}
}
func TestBridgeMethodNotAllowed(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
req := httptest.NewRequest("POST", "/.well-known/tltv", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != 400 {
t.Fatalf("status = %d, want 400", w.Code)
}
}
// TestBridgeViewerCoexistence verifies that debugViewerRoutes can be
// registered on the bridge's mux without a Go 1.22 ServeMux pattern conflict.
// The viewer's "GET /{$}" must not conflict with the bridge's method-less
// "/tltv/" and "/.well-known/tltv" catch-all patterns.
func TestBridgeViewerCoexistence(t *testing.T) {
r := testBridgeRegistry(t)
srv := newBridgeServer(r, nil, nil, nil)
// Register viewer routes on the bridge's mux — this used to panic
// with "GET /" vs "/tltv/" pattern conflict before the fix.
debugViewerRoutes(srv.mux, func(_ string) map[string]interface{} {
return map[string]interface{}{"channel_name": "test"}
}, nil)
// Viewer root serves HTML
w := httptest.NewRecorder()
srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
if w.Code != 200 {
t.Errorf("GET / status = %d, want 200", w.Code)
}
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "text/html") {
t.Errorf("GET / content-type = %q, want text/html", ct)
}
// Viewer assets work
w = httptest.NewRecorder()
srv.ServeHTTP(w, httptest.NewRequest("GET", "/api/info", nil))
if w.Code != 200 {
t.Errorf("GET /api/info status = %d, want 200", w.Code)
}
// Protocol endpoint still works
w = httptest.NewRecorder()
srv.ServeHTTP(w, httptest.NewRequest("GET", "/.well-known/tltv", nil))
if w.Code != 200 {
t.Errorf("GET /.well-known/tltv status = %d, want 200", w.Code)
}
// Method rejection still works
w = httptest.NewRecorder()
srv.ServeHTTP(w, httptest.NewRequest("POST", "/tltv/v1/peers", nil))
if w.Code != 400 {
t.Errorf("POST /tltv/ status = %d, want 400", w.Code)
}
// Non-root GET returns 404, not viewer HTML
w = httptest.NewRecorder()
srv.ServeHTTP(w, httptest.NewRequest("GET", "/nonexistent", nil))
if w.Code != 404 {
t.Errorf("GET /nonexistent status = %d, want 404", w.Code)
}
}
func TestBridgeOnDemandMetadata(t *testing.T) {
dir := t.TempDir()
r := newBridgeRegistry(dir, "")
r.UpdateChannels([]bridgeChannel{{
ID: "ch1", Name: "On Demand Channel", Stream: "http://example.com/stream.m3u8",
OnDemand: true,
}})
srv := newBridgeServer(r, nil, nil, nil)
id := testBridgeChannelID(t, r)
req := httptest.NewRequest("GET", "/tltv/v1/channels/"+id, nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
var doc map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &doc)
if doc["on_demand"] != true {
t.Errorf("on_demand = %v, want true", doc["on_demand"])
}
}
func TestBridgeOriginsFromHostname(t *testing.T) {
dir := t.TempDir()
r := newBridgeRegistry(dir, "bridge.example.com:8000")
r.UpdateChannels([]bridgeChannel{{ID: "ch1", Name: "Test", Stream: "http://example.com/stream.m3u8"}})
srv := newBridgeServer(r, nil, nil, nil)
id := testBridgeChannelID(t, r)
req := httptest.NewRequest("GET", "/tltv/v1/channels/"+id, nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
var doc map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &doc)
origins, ok := doc["origins"].([]interface{})
if !ok || len(origins) != 1 || origins[0] != "bridge.example.com:8000" {
t.Errorf("origins = %v", doc["origins"])
}
}
// ---------- Private Channels ----------
func TestBridgePrivateChannel_HiddenFromNodeInfo(t *testing.T) {
dir := t.TempDir()
r := newBridgeRegistry(dir, "")
r.UpdateChannels([]bridgeChannel{
{ID: "pub", Name: "Public", Stream: "http://example.com/pub.m3u8"},
{ID: "priv", Name: "Private", Stream: "http://example.com/priv.m3u8", Access: "token", Token: "secret123"},
})
srv := newBridgeServer(r, nil, nil, nil)
req := httptest.NewRequest("GET", "/.well-known/tltv", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
channels := resp["channels"].([]interface{})
if len(channels) != 1 {
t.Fatalf("expected 1 public channel in node info, got %d", len(channels))
}
ch := channels[0].(map[string]interface{})
if ch["name"] != "Public" {
t.Errorf("visible channel name = %v", ch["name"])
}
}
func TestBridgePrivateChannel_RequiresToken(t *testing.T) {
dir := t.TempDir()
r := newBridgeRegistry(dir, "")
r.UpdateChannels([]bridgeChannel{
{ID: "priv", Name: "Private", Stream: "http://example.com/priv.m3u8", Access: "token", Token: "secret123"},
})
srv := newBridgeServer(r, nil, nil, nil)
var privID string
for _, ch := range r.ListChannels() {
privID = ch.ChannelID
}
// No token -> 403
req := httptest.NewRequest("GET", "/tltv/v1/channels/"+privID, nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != 403 {
t.Errorf("no token: status = %d, want 403", w.Code)
}
// Wrong token -> 403
req = httptest.NewRequest("GET", "/tltv/v1/channels/"+privID+"?token=wrong", nil)
w = httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != 403 {
t.Errorf("wrong token: status = %d, want 403", w.Code)
}
// Correct token -> 200