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
|
package main
import (
"context"
"database/sql"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode"
)
type server struct {
db *sql.DB
base string // e.g. https://mediathek-newpipe.softwaregardening.org, no trailing slash
host string // host part of base
now func() time.Time
sub *http.Client
thumbs *thumbs
}
func runServe(args []string) error {
fs := flag.NewFlagSet("serve", flag.ExitOnError)
dbPath := fs.String("db", "", "SQLite database written by `mediathek import`")
addr := fs.String("addr", "127.0.0.1:8781", "listen address")
base := fs.String("base-url", "", "public base URL, e.g. https://mediathek-newpipe.softwaregardening.org")
fs.Parse(args)
if *dbPath == "" || *base == "" {
return fmt.Errorf("--db and --base-url are required")
}
db, err := openDB(*dbPath, readBusyTimeout)
if err != nil {
return err
}
defer db.Close()
wdb, err := openWriteDB(*dbPath)
if err != nil {
return err
}
defer wdb.Close()
s, err := newServer(db, *base)
if err != nil {
return err
}
s.thumbs = newThumbs(wdb)
srv := &http.Server{
Addr: *addr,
Handler: s.routes(),
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 60 * time.Second,
}
log.Printf("listening on %s as %s", *addr, s.base)
return srv.ListenAndServe()
}
func newServer(db *sql.DB, base string) (*server, error) {
u, err := url.Parse(strings.TrimRight(base, "/"))
if err != nil || u.Host == "" {
return nil, fmt.Errorf("bad --base-url %q", base)
}
return &server{
db: db,
base: u.String(),
host: u.Host,
now: time.Now,
sub: &http.Client{Timeout: subtitleTimeout},
}, nil
}
func (s *server) routes() http.Handler {
m := http.NewServeMux()
m.HandleFunc("GET /api/v1/config", s.handleConfig)
m.HandleFunc("GET /api/v1/config/about", s.handleConfig)
m.HandleFunc("GET /api/v1/videos", s.handleVideos)
m.HandleFunc("GET /api/v1/videos/{id}", s.handleVideo)
m.HandleFunc("GET /api/v1/videos/{id}/description", s.handleDescription)
m.HandleFunc("GET /api/v1/videos/{id}/captions", s.handleCaptions)
m.HandleFunc("GET /api/v1/videos/{id}/chapters", constJSON(`{"chapters":[]}`))
m.HandleFunc("GET /api/v1/videos/{id}/storyboards", constJSON(`{"storyboards":[]}`))
m.HandleFunc("GET /api/v1/videos/{id}/comment-threads", constJSON(`{"total":0,"totalNotDeletedComments":0,"data":[]}`))
m.HandleFunc("GET /api/v1/search/videos", s.handleSearchVideos)
m.HandleFunc("GET /api/v1/search/video-channels", s.handleSearchChannels)
m.HandleFunc("GET /api/v1/search/video-playlists", constJSON(`{"total":0,"data":[]}`))
m.HandleFunc("GET /api/v1/video-channels/{name}", s.handleChannel)
m.HandleFunc("GET /api/v1/video-channels/{name}/videos", s.handleChannelVideos)
m.HandleFunc("GET /api/v1/video-channels/{name}/video-playlists", constJSON(`{"total":0,"data":[]}`))
m.HandleFunc("GET /api/v1/accounts/{name}", s.handleAccount)
m.HandleFunc("GET /api/v1/accounts/{name}/videos", s.handleAccountVideos)
m.HandleFunc("GET /api/v1/accounts/{name}/video-channels", s.handleAccountChannels)
m.HandleFunc("GET /api/v1/accounts/{name}/video-playlists", constJSON(`{"total":0,"data":[]}`))
m.HandleFunc("GET /hls/{id}/master.m3u8", s.handleMaster)
m.HandleFunc("GET /hls/{id}/{h}", s.handleVariant)
m.HandleFunc("GET /f/{id}/{file}", s.handleFile)
m.HandleFunc("GET /remux/{id}/{file}", s.handleRemux)
m.HandleFunc("GET /sub/{file}", s.handleSubtitle)
m.HandleFunc("GET /thumb/{file}", s.handleThumb)
m.HandleFunc("GET /logos/{file}", handleLogo)
m.HandleFunc("GET /w/{id}", s.handleWatchPage)
m.HandleFunc("GET /videos/watch/{id}", s.handleWatchPage)
m.HandleFunc("GET /videos/embed/{id}", s.handleWatchPage)
m.HandleFunc("GET /c/{name}", s.handleChannelPage)
m.HandleFunc("GET /c/{name}/videos", s.handleChannelPage)
m.HandleFunc("GET /video-channels/{name}", s.handleChannelPage)
m.HandleFunc("GET /a/{name}", s.handleAccountPage)
m.HandleFunc("GET /accounts/{name}", s.handleAccountPage)
m.HandleFunc("GET /{$}", s.handleIndex)
return logRequests(m)
}
// ---------------------------------------------------------------------------
// helpers
var errNotFound = errors.New("not found")
// liveGen reads the live generation id; one indexed lookup per request is
// what lets a new generation go live without a restart.
func (s *server) liveGen(ctx context.Context) (int64, error) {
var g int64
err := s.db.QueryRowContext(ctx, `SELECT id FROM generation WHERE state='live'`).Scan(&g)
if err == sql.ErrNoRows {
return 0, fmt.Errorf("no film list imported yet: %w", errNotFound)
}
return g, err
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.Encode(v)
}
func constJSON(body string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write([]byte(body))
}
}
// fail answers with PeerTube's error shape ({"error": …}; NewPipe reads it).
func fail(w http.ResponseWriter, r *http.Request, err error) {
code := http.StatusInternalServerError
if errors.Is(err, errNotFound) {
code = http.StatusNotFound
} else if errors.Is(err, context.Canceled) {
return
} else {
log.Printf("%s %s: %v", r.Method, r.URL, err)
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
msg := err.Error()
if code == http.StatusInternalServerError {
msg = "internal error"
}
json.NewEncoder(w).Encode(map[string]any{"error": msg, "status": code})
}
// page reads PeerTube's start/count, count capped at 100 like PeerTube.
func page(r *http.Request) (start, count int) {
start, _ = strconv.Atoi(r.URL.Query().Get("start"))
count, _ = strconv.Atoi(r.URL.Query().Get("count"))
if start < 0 {
start = 0
}
if count <= 0 {
count = 15
}
return start, min(count, 100)
}
// stripHost drops an "@host" suffix: NewPipe builds uploader URLs as
// accounts/{name}@{host}.
func stripHost(name string) string {
if i := strings.IndexByte(name, '@'); i >= 0 {
return name[:i]
}
return name
}
// ---------------------------------------------------------------------------
// lookups
// findVideo resolves a uuid in the live generation, following dedup aliases.
func (s *server) findVideo(ctx context.Context, id string) (row, error) {
g, err := s.liveGen(ctx)
if err != nil {
return row{}, err
}
for range 2 {
r, err := scanRow(s.db.QueryRowContext(ctx, `SELECT `+rowCols+` FROM video WHERE gen=? AND uuid=?`, g, id))
if err == nil {
return r, nil
}
if err != sql.ErrNoRows {
return row{}, err
}
var target string
err = s.db.QueryRowContext(ctx, `SELECT target FROM alias WHERE gen=? AND uuid=?`, g, id).Scan(&target)
if err == sql.ErrNoRows {
break
}
if err != nil {
return row{}, err
}
id = target
}
return row{}, fmt.Errorf("video %s: %w", id, errNotFound)
}
type chanRow struct {
Name, Family, Display, Senders string
Videos int
}
// findChannel resolves a channel name, falling back through
// familySuccessors if the family it names was split since.
func (s *server) findChannel(ctx context.Context, g int64, name string) (chanRow, error) {
names := []string{name}
for old, succ := range familySuccessors {
if rest, ok := strings.CutPrefix(name, old+"-"); ok {
for _, n := range succ {
names = append(names, n+"-"+rest)
}
}
}
for _, n := range names {
var c chanRow
err := s.db.QueryRowContext(ctx, `SELECT name, family, display, senders, videos FROM channel WHERE gen=? AND name=?`, g, n).
Scan(&c.Name, &c.Family, &c.Display, &c.Senders, &c.Videos)
if err == nil {
return c, nil
}
if err != sql.ErrNoRows {
return c, err
}
}
return chanRow{}, fmt.Errorf("channel %s: %w", name, errNotFound)
}
type accRow struct {
Name, Display string
Channels, Videos int
}
func (s *server) findAccount(ctx context.Context, g int64, name string) (accRow, error) {
names := append([]string{name}, familySuccessors[name]...)
for _, n := range names {
var a accRow
err := s.db.QueryRowContext(ctx, `SELECT name, display, channels, videos FROM account WHERE gen=? AND name=?`, g, n).
Scan(&a.Name, &a.Display, &a.Channels, &a.Videos)
if err == nil {
return a, nil
}
if err != sql.ErrNoRows {
return a, err
}
}
return accRow{}, fmt.Errorf("account %s: %w", name, errNotFound)
}
func firstSender(senders string) string {
s, _, _ := strings.Cut(senders, ",")
return s
}
// videoList runs a video query (which must select rowCols and take the
// generation and "now" as its first two arguments, then LIMIT/OFFSET) and
// renders a PeerTube list with the given total.
func (s *server) videoList(w http.ResponseWriter, r *http.Request, total int, q string, args ...any) {
start, count := page(r)
rows, err := scanRows(s.db.QueryContext(r.Context(), q+` LIMIT ? OFFSET ?`, append(args, count, start)...))
if err != nil {
fail(w, r, err)
return
}
out := list[apiVideo]{Total: total, Data: []apiVideo{}}
for i := range rows {
v, _ := s.video(&rows[i], false)
out.Data = append(out.Data, v)
}
writeJSON(w, out)
}
// ---------------------------------------------------------------------------
// API handlers
func (s *server) handleConfig(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{
"instance": map[string]any{
"name": "Mediathek",
"shortDescription": "Die Mediatheken von ARD, ZDF, ORF, SRF, ARTE & Co. aus der MediathekView-Filmliste, als PeerTube-Instanz für NewPipe.",
"isNSFW": false,
"defaultNSFWPolicy": "display",
},
"serverVersion": "6.0.0",
"search": map[string]any{
"remoteUri": map[string]any{"users": false, "anonymous": false},
},
"signup": map[string]any{"allowed": false},
})
}
func (s *server) handleVideos(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
fail(w, r, err)
return
}
var total int
s.db.QueryRowContext(r.Context(), `SELECT videos FROM generation WHERE id=?`, g).Scan(&total)
// Every sort (trending, most liked, recent, local) is "newest first":
// there are no views or likes to sort by.
s.videoList(w, r, total, `SELECT `+rowCols+` FROM video WHERE gen=? AND published<=? ORDER BY published DESC`,
g, s.now().Unix())
}
func (s *server) handleVideo(w http.ResponseWriter, r *http.Request) {
row, err := s.findVideo(r.Context(), r.PathValue("id"))
if err != nil {
fail(w, r, err)
return
}
v, err := s.video(&row, true)
if err != nil {
fail(w, r, err)
return
}
writeJSON(w, v)
}
func (s *server) handleDescription(w http.ResponseWriter, r *http.Request) {
row, err := s.findVideo(r.Context(), r.PathValue("id"))
if err != nil {
fail(w, r, err)
return
}
writeJSON(w, map[string]string{"description": s.description(&row)})
}
func (s *server) handleCaptions(w http.ResponseWriter, r *http.Request) {
row, err := s.findVideo(r.Context(), r.PathValue("id"))
if err != nil {
fail(w, r, err)
return
}
out := list[any]{Data: []any{}}
if row.Subtitle != "" {
lang := language(row.Sender)
out.Total = 1
out.Data = append(out.Data, map[string]any{
"language": lang,
"captionPath": "/sub/" + row.UUID + "-" + lang.ID.(string) + ".vtt",
"automaticallyGenerated": false,
"updatedAt": iso(row.Published),
})
}
writeJSON(w, out)
}
func (s *server) handleChannel(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
fail(w, r, err)
return
}
c, err := s.findChannel(r.Context(), g, stripHost(r.PathValue("name")))
if err != nil {
fail(w, r, err)
return
}
writeJSON(w, s.channel(c.Name, c.Display, c.Family, firstSender(c.Senders), c.Videos))
}
func (s *server) handleChannelVideos(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
fail(w, r, err)
return
}
c, err := s.findChannel(r.Context(), g, stripHost(r.PathValue("name")))
if err != nil {
fail(w, r, err)
return
}
s.videoList(w, r, c.Videos, `SELECT `+rowCols+` FROM video WHERE gen=? AND published<=? AND channel=? ORDER BY published DESC`,
g, s.now().Unix(), c.Name)
}
func (s *server) handleAccount(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
fail(w, r, err)
return
}
a, err := s.findAccount(r.Context(), g, stripHost(r.PathValue("name")))
if err != nil {
fail(w, r, err)
return
}
writeJSON(w, apiAccount{
ID: numericID("account:" + a.Name),
Name: a.Name,
DisplayName: a.Display,
Host: s.host,
URL: s.base + "/accounts/" + a.Name,
Description: fmt.Sprintf("%s — %d Sendungen, %d Videos.", a.Display, a.Channels, a.Videos),
Avatars: familyLogo(a.Name),
})
}
func (s *server) handleAccountVideos(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
fail(w, r, err)
return
}
a, err := s.findAccount(r.Context(), g, stripHost(r.PathValue("name")))
if err != nil {
fail(w, r, err)
return
}
s.videoList(w, r, a.Videos, `SELECT `+rowCols+` FROM video WHERE gen=? AND published<=? AND family=? ORDER BY published DESC`,
g, s.now().Unix(), a.Name)
}
// handleAccountChannels lists an account's channels, most recently updated
// first.
func (s *server) handleAccountChannels(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
fail(w, r, err)
return
}
a, err := s.findAccount(r.Context(), g, stripHost(r.PathValue("name")))
if err != nil {
fail(w, r, err)
return
}
start, count := page(r)
s.channelList(w, r, a.Channels, `SELECT name, family, display, senders, videos FROM channel
WHERE gen=? AND family=? ORDER BY latest DESC LIMIT ? OFFSET ?`, g, a.Name, count, start)
}
func (s *server) channelList(w http.ResponseWriter, r *http.Request, total int, q string, args ...any) {
rows, err := s.db.QueryContext(r.Context(), q, args...)
if err != nil {
fail(w, r, err)
return
}
defer rows.Close()
out := list[apiChannel]{Total: total, Data: []apiChannel{}}
for rows.Next() {
var c chanRow
if err := rows.Scan(&c.Name, &c.Family, &c.Display, &c.Senders, &c.Videos); err != nil {
fail(w, r, err)
return
}
out.Data = append(out.Data, s.channel(c.Name, c.Display, c.Family, firstSender(c.Senders), c.Videos))
}
if err := rows.Err(); err != nil {
fail(w, r, err)
return
}
writeJSON(w, out)
}
// ftsQuery turns user input into an FTS5 query: every word must match as a
// prefix. Words are quoted, so FTS syntax in the input is inert.
func ftsQuery(in string) string {
var terms []string
for _, w := range strings.FieldsFunc(in, func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) }) {
terms = append(terms, `"`+w+`"*`)
}
return strings.Join(terms, " ")
}
// searchCap bounds the counted total of a search: counting every match of
// a common word would cost more than the page itself.
const searchCap = 1000
func (s *server) handleSearchVideos(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
fail(w, r, err)
return
}
q := r.URL.Query()
// Related videos: NewPipe asks for tagsOneOf=<tags> and no search term.
// Our tags are the sender plus variant tags, so answer with the newest
// videos of the same sender.
if q.Get("search") == "" {
tag := q.Get("tagsOneOf")
if tag == "" {
writeJSON(w, list[apiVideo]{Data: []apiVideo{}})
return
}
s.videoList(w, r, searchCap, `SELECT `+rowCols+` FROM video WHERE gen=? AND published<=? AND sender=? ORDER BY published DESC`,
g, s.now().Unix(), tag)
return
}
fq := ftsQuery(q.Get("search"))
if fq == "" {
writeJSON(w, list[apiVideo]{Data: []apiVideo{}})
return
}
var total int
if err := s.db.QueryRowContext(r.Context(), `SELECT count(*) FROM (SELECT 1 FROM video_fts f JOIN video v ON v.rowid=f.rowid
WHERE video_fts MATCH ? AND v.gen=? LIMIT ?)`, fq, g, searchCap).Scan(&total); err != nil {
fail(w, r, err)
return
}
cols := strings.ReplaceAll("v."+rowCols, ", ", ", v.")
s.videoList(w, r, total, `SELECT `+cols+` FROM video_fts f JOIN video v ON v.rowid=f.rowid
WHERE v.gen=? AND v.published<=? AND video_fts MATCH ? ORDER BY v.published DESC`, g, s.now().Unix(), fq)
}
func (s *server) handleSearchChannels(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
fail(w, r, err)
return
}
fq := ftsQuery(r.URL.Query().Get("search"))
if fq == "" {
writeJSON(w, list[apiChannel]{Data: []apiChannel{}})
return
}
var total int
if err := s.db.QueryRowContext(r.Context(), `SELECT count(*) FROM channel_fts f JOIN channel c ON c.rowid=f.rowid
WHERE channel_fts MATCH ? AND c.gen=?`, fq, g).Scan(&total); err != nil {
fail(w, r, err)
return
}
start, count := page(r)
s.channelList(w, r, total, `SELECT c.name, c.family, c.display, c.senders, c.videos FROM channel_fts f JOIN channel c ON c.rowid=f.rowid
WHERE channel_fts MATCH ? AND c.gen=? ORDER BY c.videos DESC LIMIT ? OFFSET ?`, fq, g, count, start)
}
// ---------------------------------------------------------------------------
// media: redirects and generated playlists. No video byte passes through
// here, and nothing is fetched upstream.
func (s *server) filesOf(w http.ResponseWriter, r *http.Request) (row, []File, bool) {
row, err := s.findVideo(r.Context(), r.PathValue("id"))
if err != nil {
fail(w, r, err)
return row, nil, false
}
fs, err := decodeFiles(row.Files)
if err != nil {
fail(w, r, err)
return row, nil, false
}
return row, fs, true
}
// fileByHeight reads "<h>.<ext>" or "<h>.m3u8".
func fileByHeight(fs []File, name string) (File, bool) {
h, err := strconv.Atoi(strings.TrimSuffix(name, name[strings.LastIndexByte(name, '.'):]))
if err != nil {
return File{}, false
}
for _, f := range fs {
if f.Height == h {
return f, true
}
}
return File{}, false
}
// bandwidth is a plausible BANDWIDTH for a height; players only use it to
// order and pick variants.
func bandwidth(h int) int {
switch {
case h <= 0:
return 128000
case h <= 288:
return 500000
case h <= 360:
return 900000
case h <= 540:
return 1800000
case h <= 576:
return 2400000
case h <= 720:
return 3500000
case h <= 1080:
return 6000000
default:
return 12000000
}
}
// handleMaster writes an HLS master from the database. For KindMaster the
// upstream already has one; we redirect to it.
func (s *server) handleMaster(w http.ResponseWriter, r *http.Request) {
row, fs, ok := s.filesOf(w, r)
if !ok {
return
}
if len(fs) == 0 {
fail(w, r, errNotFound)
return
}
if row.Kind == KindMaster {
http.Redirect(w, r, fs[0].URL, http.StatusFound)
return
}
w.Header().Set("Content-Type", "application/vnd.apple.mpegurl")
w.Header().Set("Cache-Control", "public, max-age=3600")
var b strings.Builder
b.WriteString("#EXTM3U\n#EXT-X-VERSION:3\n")
for _, f := range fs {
fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d,RESOLUTION=%dx%d\n%s\n",
bandwidth(f.Height), f.Height*16/9/2*2, f.Height, f.URL)
}
w.Write([]byte(b.String()))
}
// handleVariant serves the per-resolution HLS URL NewPipe derives from
// playlistUrl ("master" → "<h>"): a redirect to the upstream variant, or
// for a ready-made upstream master, to that master.
func (s *server) handleVariant(w http.ResponseWriter, r *http.Request) {
_, fs, ok := s.filesOf(w, r)
if !ok {
return
}
name := r.PathValue("h")
if !strings.HasSuffix(name, ".m3u8") {
fail(w, r, errNotFound)
return
}
f, ok := fileByHeight(fs, name)
if !ok {
fail(w, r, fmt.Errorf("no variant %s: %w", name, errNotFound))
return
}
http.Redirect(w, r, f.URL, http.StatusFound)
}
// handleFile redirects to a progressive file whose upstream URL cannot be
// handed out directly (query string, or no .mp4/.mp3 at the end).
func (s *server) handleFile(w http.ResponseWriter, r *http.Request) {
_, fs, ok := s.filesOf(w, r)
if !ok {
return
}
f, ok := fileByHeight(fs, r.PathValue("file"))
if !ok {
fail(w, r, errNotFound)
return
}
http.Redirect(w, r, f.URL, http.StatusFound)
}
func (s *server) handleRemux(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Dieses Video gibt es beim Sender nur als Stream (HLS); Herunterladen wird nicht unterstützt.\n" +
"This video is only available as a stream (HLS); downloading is not supported.\n"))
}
// ---------------------------------------------------------------------------
// HTML pages, so a shared link opens in a browser too.
var pageTmpl = template.Must(template.New("page").Parse(`<!doctype html>
<html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}} – Mediathek</title>
<style>body{font-family:sans-serif;max-width:40em;margin:2em auto;padding:0 1em;line-height:1.5}pre{white-space:pre-wrap;font-family:inherit}</style>
</head><body>
<h1>{{.Title}}</h1>
{{with .Sub}}<p>{{.}}</p>{{end}}
{{with .Text}}<pre>{{.}}</pre>{{end}}
{{with .Links}}<ul>{{range .}}<li><a href="{{.Href}}">{{.Text}}</a></li>{{end}}</ul>{{end}}
<p><small>Diese Seite ist eine PeerTube-kompatible Schnittstelle zur MediathekView-Filmliste. Links hierher in <a href="https://newpipe.net">NewPipe</a> öffnen.</small></p>
</body></html>
`))
type pageLink struct{ Href, Text string }
type pageData struct {
Title, Sub, Text string
Links []pageLink
}
func (s *server) render(w http.ResponseWriter, d pageData) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
pageTmpl.Execute(w, d)
}
func (s *server) handleWatchPage(w http.ResponseWriter, r *http.Request) {
row, err := s.findVideo(r.Context(), r.PathValue("id"))
if err != nil {
http.Error(w, "Video nicht gefunden", http.StatusNotFound)
return
}
d := pageData{
Title: row.Title,
Sub: row.Topic + " · " + row.Sender + " · " + time.Unix(row.Published, 0).In(berlin).Format("02.01.2006 15:04"),
Text: s.description(&row),
Links: []pageLink{{"/c/" + row.Channel, "Alle Folgen: " + row.Topic}},
}
if row.Website != "" {
d.Links = append([]pageLink{{row.Website, "Beim Sender ansehen"}}, d.Links...)
}
s.render(w, d)
}
func (s *server) handleChannelPage(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
c, err := s.findChannel(r.Context(), g, stripHost(r.PathValue("name")))
if err != nil {
http.Error(w, "Sendung nicht gefunden", http.StatusNotFound)
return
}
rows, _ := scanRows(s.db.QueryContext(r.Context(), `SELECT `+rowCols+` FROM video WHERE gen=? AND published<=? AND channel=? ORDER BY published DESC LIMIT 50`,
g, s.now().Unix(), c.Name))
d := pageData{Title: c.Display, Sub: fmt.Sprintf("%s · %d Videos", strings.ReplaceAll(c.Senders, ",", ", "), c.Videos)}
for _, v := range rows {
d.Links = append(d.Links, pageLink{"/w/" + v.UUID, time.Unix(v.Published, 0).In(berlin).Format("02.01.2006") + " – " + v.Title})
}
s.render(w, d)
}
func (s *server) handleAccountPage(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
a, err := s.findAccount(r.Context(), g, stripHost(r.PathValue("name")))
if err != nil {
http.Error(w, "Sender nicht gefunden", http.StatusNotFound)
return
}
rows, err := s.db.QueryContext(r.Context(), `SELECT name, display, videos FROM channel WHERE gen=? AND family=? ORDER BY latest DESC LIMIT 200`, g, a.Name)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
defer rows.Close()
d := pageData{Title: a.Display, Sub: fmt.Sprintf("%d Sendungen · %d Videos", a.Channels, a.Videos)}
for rows.Next() {
var name, display string
var n int
rows.Scan(&name, &display, &n)
d.Links = append(d.Links, pageLink{"/c/" + name, fmt.Sprintf("%s (%d)", display, n)})
}
s.render(w, d)
}
func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) {
g, err := s.liveGen(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
var gen Generation
gen, err = scanGen(s.db.QueryRowContext(r.Context(), `SELECT `+genCols+` FROM generation WHERE id=?`, g))
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
rows, err := s.db.QueryContext(r.Context(), `SELECT name, display, videos FROM account WHERE gen=? ORDER BY videos DESC`, g)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
defer rows.Close()
d := pageData{
Title: "Mediathek",
Sub: fmt.Sprintf("%d Videos in %d Sendungen · Filmliste vom %s",
gen.Videos, gen.Channels, gen.ListCreated.In(berlin).Format("02.01.2006 15:04")),
Text: "In NewPipe als PeerTube-Instanz hinzufügen: " + s.base,
}
for rows.Next() {
var name, display string
var n int
rows.Scan(&name, &display, &n)
d.Links = append(d.Links, pageLink{"/a/" + name, fmt.Sprintf("%s (%d)", display, n)})
}
s.render(w, d)
}
var berlin = func() *time.Location {
l, err := time.LoadLocation("Europe/Berlin")
if err != nil {
return time.UTC
}
return l
}()
// ---------------------------------------------------------------------------
type statusWriter struct {
http.ResponseWriter
code int
}
func (w *statusWriter) WriteHeader(c int) { w.code = c; w.ResponseWriter.WriteHeader(c) }
func logRequests(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t := time.Now()
sw := &statusWriter{ResponseWriter: w, code: 200}
h.ServeHTTP(sw, r)
log.Printf("%d %s %s %s", sw.code, r.Method, r.URL.RequestURI(), time.Since(t).Round(time.Millisecond))
})
}
|