forked from averygan/reclip
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1539 lines (1409 loc) · 43.4 KB
/
Copy pathmain.go
File metadata and controls
1539 lines (1409 loc) · 43.4 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 (
"bufio"
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"embed"
"encoding/hex"
"encoding/json"
"fmt"
"image"
"image/color"
"image/jpeg"
"io"
"io/fs"
"log"
"math"
"mime"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
)
//go:embed templates static
var content embed.FS
const (
infoTimeout = 60 * time.Second
downloadTimeout = 5 * time.Minute
)
// Preferred playback heights offered as the "default resolution" setting. Keys
// are the accepted wire values.
var defaultHeights = map[string]int{
"1080p": 1080,
"720p": 720,
"480p": 480,
"360p": 360,
}
// settingsFile sits next to the binary. A var (not a const) so tests can point
// it somewhere disposable.
var settingsFile = "settings.json"
var (
downloadDir string
ytdlpPath string
ffmpegPath string
resolution string // preferred height for the auto-selected quality, e.g. "720p"
settingsMu sync.RWMutex
jobsMu sync.RWMutex
jobs = map[string]*job{}
// Server-Sent Events: subscribed pages get pushed job snapshots instead of
// polling /api/jobs. Each client holds only the *newest* snapshot (see
// sseClient), so a backlog can delay updates but never drop the last one —
// dropping it is what left finished downloads stuck at their final percent.
sseMu sync.Mutex
sseClients = map[*sseClient]struct{}{}
)
// sseClient is one subscribed browser. `queued` is replaced (not appended) on
// every update, so a client that is slow to read always sees the latest state;
// `wake` only signals "there is something to write".
type sseClient struct {
mu sync.Mutex
queued []byte
wake chan struct{}
}
func newSSEClient() *sseClient { return &sseClient{wake: make(chan struct{}, 1)} }
// deliver stores payload as the pending snapshot and wakes the writer.
func (c *sseClient) deliver(payload []byte) {
c.mu.Lock()
c.queued = payload
c.mu.Unlock()
select {
case c.wake <- struct{}{}:
default: // already signalled — the writer will pick the newest payload up
}
}
// take returns the pending snapshot, or nil when there is nothing new.
func (c *sseClient) take() []byte {
c.mu.Lock()
defer c.mu.Unlock()
p := c.queued
c.queued = nil
return p
}
func getDownloadDir() string {
settingsMu.RLock()
defer settingsMu.RUnlock()
return downloadDir
}
func getYtdlpPath() string {
settingsMu.RLock()
defer settingsMu.RUnlock()
return ytdlpPath
}
func getFfmpegPath() string {
settingsMu.RLock()
defer settingsMu.RUnlock()
return ffmpegPath
}
func getResolution() string {
settingsMu.RLock()
defer settingsMu.RUnlock()
return resolution
}
// getResolutionHeight returns the preferred pixel height, or 0 when there is no
// preference ("best available").
func getResolutionHeight() int {
settingsMu.RLock()
defer settingsMu.RUnlock()
return defaultHeights[resolution]
}
// isExecutable reports whether path points to an executable regular file.
func isExecutable(path string) bool {
if path == "" {
return false
}
info, err := os.Stat(path)
if err != nil || info.IsDir() {
return false
}
return runtime.GOOS == "windows" || info.Mode()&0o111 != 0
}
type settings struct {
Dir string `json:"dir"`
Ytdlp string `json:"ytdlp"`
Ffmpeg string `json:"ffmpeg"`
Resolution string `json:"resolution"`
}
type job struct {
id string
url string
format string // video | audio
status string // downloading | done | error
progress float64
title string
file string
filename string
error string
duration float64 // media length in seconds, when the client knew it
created time.Time
cancel context.CancelFunc
}
type formatInfo struct {
ID string `json:"id"`
Label string `json:"label"`
Height int `json:"height"`
}
type ytdlpFormat struct {
FormatID string `json:"format_id"`
Height int `json:"height"`
Vcodec string `json:"vcodec"`
TBR float64 `json:"tbr"`
}
type ytdlpInfo struct {
Title string `json:"title"`
Thumbnail string `json:"thumbnail"`
Duration any `json:"duration"`
Uploader string `json:"uploader"`
Formats []ytdlpFormat `json:"formats"`
}
type playlistResponse struct {
URLs []string `json:"urls"`
}
type downloadRequest struct {
URL string `json:"url"`
Format string `json:"format"`
FormatID string `json:"format_id"`
Title string `json:"title"`
Filename string `json:"filename"`
Start string `json:"start"`
End string `json:"end"`
// Duration is the media length in seconds reported by /api/info. It lets
// us turn ffmpeg's read position into a real percentage.
Duration float64 `json:"duration"`
}
func init() {
_ = mime.AddExtensionType(".svg", "image/svg+xml")
}
func main() {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
var s settings
if loaded, err := loadSettings(); err == nil {
s = loaded
}
// Resolve the save directory: DOWNLOAD_DIR env > settings.json > ./downloads.
downloadDir = os.Getenv("DOWNLOAD_DIR")
if downloadDir == "" && s.Dir != "" {
downloadDir = s.Dir
}
if downloadDir == "" {
downloadDir = filepath.Join(dir, "downloads")
}
if err := os.MkdirAll(downloadDir, 0o755); err != nil {
log.Fatal(err)
}
// Resolve yt-dlp: a path set in settings.json wins; else the one on PATH,
// else an auto-downloaded standalone build (no Python needed).
// `=` (not `:=`) assigns the package-level ytdlpPath used by runCmd/download.
// `:=` would shadow it with a main-local copy and leave the global "" (that
// bug surfaced as "exec: no command").
var managed bool
if s.Ytdlp != "" && isExecutable(s.Ytdlp) {
ytdlpPath = s.Ytdlp
managed = false // user-configured path — not self-updated
} else {
ytdlpPath, managed = resolveYtdlp()
}
if ytdlpPath == "" {
log.Printf("WARNING: yt-dlp unavailable — downloads will fail. Install it or let ReClip download it (needs network).")
} else if os.Getenv("RECLIP_NO_UPDATE") == "" && managed {
// Only self-update the standalone build ReClip owns. A system yt-dlp
// (Homebrew, OS package) is owned by its package manager — running
// `yt-dlp -U` on it refuses with exit code 100.
go func() {
log.Printf("Updating yt-dlp...")
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
if err := exec.CommandContext(ctx, ytdlpPath, "-U").Run(); err != nil {
log.Printf("couldn't update yt-dlp: %v", err)
}
}()
} else if !managed && os.Getenv("RECLIP_NO_UPDATE") == "" {
log.Printf("Using yt-dlp (%s).", ytdlpPath)
}
// Resolve ffmpeg: a path set in settings.json wins, else the one on PATH.
if s.Ffmpeg != "" && isExecutable(s.Ffmpeg) {
ffmpegPath = s.Ffmpeg
} else if p, err := exec.LookPath("ffmpeg"); err == nil {
ffmpegPath = p
}
if ffmpegPath == "" {
log.Printf("WARNING: ffmpeg not found — MP4 merging and time-range excerpts will fail. Install ffmpeg.")
}
// Restore the default-resolution preference; anything unknown falls back to
// no preference (best available).
if _, ok := defaultHeights[s.Resolution]; ok {
resolution = s.Resolution
}
// Write the resolved settings back into settings.json so the config file
// records exactly which binaries and preferences are in use.
_ = saveSettings(settings{Dir: getDownloadDir(), Ytdlp: ytdlpPath, Ffmpeg: ffmpegPath, Resolution: resolution})
mux := http.NewServeMux()
mux.HandleFunc("/", handleIndex)
mux.HandleFunc("/static/", handleStatic)
mux.HandleFunc("/privacy", handlePrivacy)
mux.HandleFunc("/api/thumb", handleThumb)
mux.HandleFunc("/api/info", handleInfo)
mux.HandleFunc("/api/playlist", handlePlaylist)
mux.HandleFunc("/api/download", handleDownload)
mux.HandleFunc("/api/status/", handleStatus)
mux.HandleFunc("/api/file/", handleFile)
mux.HandleFunc("/api/jobs", handleJobs)
mux.HandleFunc("/api/events", handleEvents)
mux.HandleFunc("/api/job/", handleJobDelete)
mux.HandleFunc("/api/settings", handleSettings)
host := os.Getenv("HOST")
if host == "" {
host = "127.0.0.1"
}
port := os.Getenv("PORT")
if port == "" {
port = "8899"
}
addr := host + ":" + port
log.Printf("ReClip is running at http://%s", addr)
log.Fatal(http.ListenAndServe(addr, withCORS(mux)))
}
// withCORS allows cross-origin callers — e.g. the Chrome companion extension
// fetching from a non-matching server address (LAN IP, remote host). The
// frontend itself is same-origin, so the permissive `*` is harmless.
func withCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
// --- helpers ---
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func readJSON(r *http.Request, v any) error {
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(v)
}
func runCmd(ctx context.Context, args ...string) ([]byte, string, error) {
cmd := exec.CommandContext(ctx, getYtdlpPath(), args...)
var out, errBuf bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &errBuf
err := cmd.Run()
return out.Bytes(), errBuf.String(), err
}
// cmdError mirrors the Python backend: surface the last stderr line.
func cmdError(stderr string, err error) string {
if stderr = strings.TrimSpace(stderr); stderr != "" {
lines := strings.Split(stderr, "\n")
return strings.TrimSpace(lines[len(lines)-1])
}
return err.Error()
}
// --- yt-dlp management ---
// ytdlpDownloadURL is the base for fetching the standalone build and its
// checksums. A var (not const) so tests can point it at a local server.
var ytdlpDownloadURL = "https://github.com/yt-dlp/yt-dlp/releases/latest/download"
// resolveYtdlp returns a usable yt-dlp executable and whether ReClip manages it.
// When a system yt-dlp is on PATH (e.g. Homebrew), it's returned un-managed
// (autoUpdate=false): that install is owned by a package manager, so `-U` is not
// the right updater and can fail with exit code 100. Otherwise ReClip
// downloads/owns a standalone build and self-updates it.
func resolveYtdlp() (path string, autoUpdate bool) {
if p, err := exec.LookPath("yt-dlp"); err == nil {
return p, false
}
binDir := os.Getenv("RECLIP_BIN_DIR")
if binDir == "" {
dir, err := os.Getwd()
if err != nil {
return "", false
}
binDir = filepath.Join(dir, "bin")
}
local := filepath.Join(binDir, "yt-dlp")
if runtime.GOOS == "windows" {
local += ".exe"
}
if info, err := os.Stat(local); err == nil && !info.IsDir() {
return local, true
}
asset, ok := ytdlpAsset()
if !ok {
return "", false
}
if err := os.MkdirAll(binDir, 0o755); err != nil {
log.Printf("could not create bin dir %s: %v", binDir, err)
return "", false
}
url := ytdlpDownloadURL + "/" + asset
log.Printf("yt-dlp not found — downloading %s ...", url)
if err := downloadBinary(url, local, asset); err != nil {
log.Printf("failed to download yt-dlp: %v", err)
return "", false
}
return local, true
}
// ytdlpAsset maps the current platform to a release asset name.
func ytdlpAsset() (string, bool) {
switch runtime.GOOS {
case "linux":
switch runtime.GOARCH {
case "amd64":
return "yt-dlp", true
case "arm64":
return "yt-dlp_linux_aarch64", true
}
case "darwin":
return "yt-dlp_macos", true // universal2: covers amd64 + arm64
case "windows":
if runtime.GOARCH == "arm64" {
return "yt-dlp_arm64.exe", true
}
return "yt-dlp.exe", true
}
log.Printf("no prebuilt yt-dlp for %s/%s — install yt-dlp manually", runtime.GOOS, runtime.GOARCH)
return "", false
}
func downloadBinary(url, dest, asset string) error {
tmp := dest + ".part"
if err := downloadFile(url, tmp); err != nil {
return err
}
defer os.Remove(tmp)
if err := verifyChecksum(tmp, asset); err != nil {
return err
}
if runtime.GOOS != "windows" {
if err := os.Chmod(tmp, 0o755); err != nil {
return err
}
}
return os.Rename(tmp, dest)
}
func downloadFile(url, dest string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected HTTP status %d for %s", resp.StatusCode, url)
}
f, err := os.Create(dest)
if err != nil {
return err
}
_, cerr := io.Copy(f, resp.Body)
if cerr == nil {
cerr = f.Sync()
}
if err := f.Close(); err != nil {
cerr = err
}
return cerr
}
// verifyChecksum cross-checks the downloaded binary against the official
// SHA2-256SUMS file, so we never execute a tampered build.
func verifyChecksum(path, asset string) error {
resp, err := http.Get(ytdlpDownloadURL + "/SHA2-256SUMS")
if err != nil {
return fmt.Errorf("fetching checksums: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected HTTP status %d for checksums", resp.StatusCode)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
want := ""
for _, line := range bytes.Split(data, []byte("\n")) {
fields := bytes.Fields(line)
if len(fields) != 2 || string(fields[1]) != asset {
continue
}
want = strings.TrimPrefix(string(fields[0]), "sha256:")
break
}
if want == "" {
return fmt.Errorf("checksum for %s not found", asset)
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return err
}
if got := hex.EncodeToString(h.Sum(nil)); !strings.EqualFold(got, want) {
return fmt.Errorf("checksum mismatch for %s", asset)
}
return nil
}
// parseYtdlpJSON returns the first valid JSON object on stdout. With -j yt-dlp
// prints one object per line; some extractors emit several videos even with
// --no-playlist, so a plain json.Unmarshal would hit "extra data".
func parseYtdlpJSON(stdout []byte) (json.RawMessage, error) {
for _, line := range bytes.Split(stdout, []byte("\n")) {
line = bytes.TrimSpace(line)
if len(line) == 0 {
continue
}
return json.RawMessage(line), nil
}
return nil, fmt.Errorf("yt-dlp returned no data")
}
func getJob(id string) (*job, bool) {
jobsMu.RLock()
defer jobsMu.RUnlock()
j, ok := jobs[id]
return j, ok
}
func setJobStatus(j *job, status, errMsg string) {
jobsMu.Lock()
j.status = status
j.error = errMsg
jobsMu.Unlock()
broadcastJobs()
}
// finishJob is the single terminal transition (done/error). It always pushes a
// snapshot: setting j.status directly without one left the page showing the
// last streamed percentage forever.
func finishJob(j *job, status, errMsg string, progress float64) {
jobsMu.Lock()
j.status = status
j.error = errMsg
j.progress = progress
jobsMu.Unlock()
broadcastJobs()
}
func setJobProgress(j *job, p float64) {
jobsMu.Lock()
// Never move backwards: yt-dlp restarts at 0% for the audio track of a
// video+audio merge, which would yank the bar back to the start.
if p <= j.progress {
jobsMu.Unlock()
return
}
// Throttle: yt-dlp emits a progress line per fragment (dozens per second).
// Only push when the rendered percentage actually moves.
notify := p >= 100 || p-j.progress >= 0.5
j.progress = p
jobsMu.Unlock()
if notify {
broadcastJobs()
}
}
func newJobID() string {
b := make([]byte, 5)
if _, err := rand.Read(b); err != nil {
return fmt.Sprintf("%x", time.Now().UnixNano())
}
return hex.EncodeToString(b)
}
func sanitizeTitle(title string) string {
var b strings.Builder
for _, r := range title {
if !strings.ContainsRune(`\/:*?"<>|`, r) {
b.WriteRune(r)
}
}
s := strings.TrimSpace(b.String())
if s == "" {
return ""
}
runes := []rune(s)
if len(runes) > 100 {
s = string(runes[:100])
}
return strings.TrimSpace(s)
}
// resolveFinalName returns (base, ext) for the finished file: a user-supplied
// custom name wins over the resolved title; falls back to the temp file's name.
func resolveFinalName(custom, title, chosen string) (string, string) {
ext := filepath.Ext(chosen)
base := ""
if custom != "" {
base = strings.TrimSpace(sanitizeTitle(custom))
base = strings.TrimSuffix(base, filepath.Ext(base))
}
if base == "" {
base = sanitizeTitle(title)
}
if base == "" {
base = strings.TrimSuffix(filepath.Base(chosen), ext)
}
return base, ext
}
// uniquePath picks a non-colliding path under dir, appending " (n)" when the
// target already exists (e.g. two downloads given the same custom filename).
func uniquePath(dir, base, ext string) string {
p := filepath.Join(dir, base+ext)
if _, err := os.Stat(p); os.IsNotExist(err) {
return p
}
for n := 2; ; n++ {
q := filepath.Join(dir, fmt.Sprintf("%s (%d)%s", base, n, ext))
if _, err := os.Stat(q); os.IsNotExist(err) {
return q
}
}
}
// defaultFormatID picks what a freshly fetched card should start on: the
// sharpest format at or below the preferred height, so 720p lands on 720p even
// when the video also offers 1080p. When every format is taller than the
// preference (a 4K-only video with 360p wanted), the gentlest one wins.
// formats must be sorted sharpest-first; "" means there is nothing to pick.
func defaultFormatID(formats []formatInfo, prefHeight int) string {
if len(formats) == 0 {
return ""
}
if prefHeight <= 0 {
return formats[0].ID // no preference → best available
}
var withinID string
gentlest := formats[0]
for _, f := range formats {
if f.Height <= prefHeight && withinID == "" {
withinID = f.ID // sorted desc, so the first match is the sharpest
}
if f.Height < gentlest.Height {
gentlest = f
}
}
if withinID != "" {
return withinID
}
return gentlest.ID
}
func pickFile(files []string, formatChoice string) string {
ext := ".mp4"
if formatChoice == "audio" {
ext = ".mp3"
}
for _, f := range files {
if strings.EqualFold(filepath.Ext(f), ext) {
return f
}
}
return files[0]
}
func loadSettings() (settings, error) {
var s settings
data, err := os.ReadFile(settingsFile)
if err != nil {
return s, err
}
err = json.Unmarshal(data, &s)
return s, err
}
func saveSettings(s settings) error {
data, err := json.Marshal(s)
if err != nil {
return err
}
return os.WriteFile(settingsFile, data, 0o644)
}
// --- handlers ---
func handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
data, err := content.ReadFile("templates/index.html")
if err != nil {
http.Error(w, "index not found", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(data)
}
// handlePrivacy serves the static privacy-policy page. It lives under
// templates/ (embedded) like index.html, but is its own route rather than a
// sub-path of "/", so it never collides with handleIndex's "/" guard.
func handlePrivacy(w http.ResponseWriter, r *http.Request) {
data, err := content.ReadFile("templates/privacy.html")
if err != nil {
http.Error(w, "privacy policy not found", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(data)
}
// --- thumbnail compression proxy ---
//
// Cards used to point <img> straight at the source CDN. That cost bandwidth
// (full-size originals) and broke on hotlink protection (the page sent a
// Referer the CDN rejected, while a direct tab had none). This endpoint fetches
// the thumbnail server-side, downscales it to a 2x display bound, and re-encodes
// as JPEG — so the browser pulls a small same-origin image. Formats the stdlib
// can't decode (e.g. WebP) are proxied through untouched.
const (
thumbMaxW = 240 // 2x of the 120px display width
thumbMaxH = 160 // 2x of the 80px display height
thumbQuality = 80 // JPEG quality: small, still sharp
thumbFetchTo = 15 * time.Second // upstream fetch deadline
thumbMaxBytes = 8 << 20 // cap the fetched original at 8 MiB
thumbMaxSide = 5000 // reject absurdly large bitmaps
thumbCacheMaxAge = 24 * time.Hour // thumbnails are effectively immutable
)
// isSafeHost blocks URLs whose host is (or resolves to) a private, loopback, or
// link-local address, so the proxy can't be steered at internal services (SSRF).
func isSafeHost(u *url.URL) bool {
host := u.Hostname()
if ip := net.ParseIP(host); ip != nil {
return !ip.IsPrivate() && !ip.IsLoopback() &&
!ip.IsLinkLocalUnicast() && !ip.IsLinkLocalMulticast()
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
if err != nil {
return false
}
for _, a := range ips {
ip := a.IP
if ip.IsPrivate() || ip.IsLoopback() ||
ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
return false
}
}
return true
}
// fitBounds scales (w,h) down to fit within (maxW,maxH), preserving aspect.
func fitBounds(w, h, maxW, maxH int) (dw, dh int) {
if w <= 0 || h <= 0 {
return maxW, maxH
}
scale := math.Min(float64(maxW)/float64(w), float64(maxH)/float64(h))
if scale >= 1 {
return w, h
}
return int(math.Round(float64(w) * scale)), int(math.Round(float64(h) * scale))
}
// downscale averages source blocks into each destination pixel (box filter) — a
// dependency-free stand-in for a real resampler, good enough for thumbnails.
func downscale(src image.Image, dw, dh int) *image.RGBA {
sb := src.Bounds()
sw, sh := sb.Dx(), sb.Dy()
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
for y := 0; y < dh; y++ {
y0, y1 := y*sh/dh, (y+1)*sh/dh
if y1 <= y0 {
y1 = y0 + 1
}
for x := 0; x < dw; x++ {
x0, x1 := x*sw/dw, (x+1)*sw/dw
if x1 <= x0 {
x1 = x0 + 1
}
var r, g, b, a uint64
var n int
for sy := y0; sy < y1; sy++ {
for sx := x0; sx < x1; sx++ {
pr, pg, pb, pa := src.At(sb.Min.X+sx, sb.Min.Y+sy).RGBA()
r += uint64(pr)
g += uint64(pg)
b += uint64(pb)
a += uint64(pa)
n++
}
}
dst.Set(x, y, color.RGBA{
R: uint8((r / uint64(n)) >> 8),
G: uint8((g / uint64(n)) >> 8),
B: uint8((b / uint64(n)) >> 8),
A: uint8((a / uint64(n)) >> 8),
})
}
}
return dst
}
// handleThumb fetches, downscales, and re-encodes a remote thumbnail. On any
// decode/resize failure it falls back to streaming the original bytes as-is.
func handleThumb(w http.ResponseWriter, r *http.Request) {
raw := strings.TrimSpace(r.URL.Query().Get("u"))
if raw == "" {
http.Error(w, "missing u", http.StatusBadRequest)
return
}
u, err := url.Parse(raw)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") {
http.Error(w, "invalid url", http.StatusBadRequest)
return
}
if !isSafeHost(u) {
http.Error(w, "forbidden host", http.StatusForbidden)
return
}
ctx, cancel := context.WithTimeout(context.Background(), thumbFetchTo)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, "fetch failed", http.StatusBadGateway)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
http.Error(w, "upstream error", http.StatusBadGateway)
return
}
data, err := io.ReadAll(io.LimitReader(resp.Body, thumbMaxBytes))
if err != nil {
http.Error(w, "read failed", http.StatusBadGateway)
return
}
if img, format, derr := image.Decode(bytes.NewReader(data)); derr == nil {
b := img.Bounds()
if b.Dx() <= thumbMaxSide && b.Dy() <= thumbMaxSide {
dw, dh := fitBounds(b.Dx(), b.Dy(), thumbMaxW, thumbMaxH)
if dw < b.Dx() || dh < b.Dy() {
img = downscale(img, dw, dh)
}
buf := &bytes.Buffer{}
if jpeg.Encode(buf, img, &jpeg.Options{Quality: thumbQuality}) == nil {
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Cache-Control", "public, max-age="+strconv.Itoa(int(thumbCacheMaxAge.Seconds())))
w.Header().Set("X-Reclip-Thumb", format)
_, _ = w.Write(buf.Bytes())
return
}
}
}
// Unsupported/oversized format: pass the original through (still same-origin,
// so it also dodges the hotlink-Referer 404).
w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
w.Header().Set("Cache-Control", "public, max-age="+strconv.Itoa(int(thumbCacheMaxAge.Seconds())))
_, _ = w.Write(data)
}
func handleStatic(w http.ResponseWriter, r *http.Request) {
sub, err := fs.Sub(content, "static")
if err != nil {
http.NotFound(w, r)
return
}
http.StripPrefix("/static/", http.FileServer(http.FS(sub))).ServeHTTP(w, r)
}
func handleInfo(w http.ResponseWriter, r *http.Request) {
var req struct {
URL string `json:"url"`
}
if err := readJSON(r, &req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request"})
return
}
req.URL = strings.TrimSpace(req.URL)
if req.URL == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "No URL provided"})
return
}
ctx, cancel := context.WithTimeout(context.Background(), infoTimeout)
defer cancel()
stdout, stderr, err := runCmd(ctx, "--no-playlist", "-j", req.URL)
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Timed out fetching video info"})
return
}
writeJSON(w, http.StatusBadRequest, map[string]string{"error": cmdError(stderr, err)})
return
}
raw, err := parseYtdlpJSON(stdout)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
var info ytdlpInfo
if err := json.Unmarshal(raw, &info); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
// Keep the best format (highest bitrate) per resolution.
best := map[int]ytdlpFormat{}
for _, f := range info.Formats {
if f.Height <= 0 || f.Vcodec == "none" {
continue
}
cur, ok := best[f.Height]
if !ok || f.TBR > cur.TBR {
best[f.Height] = f
}
}
formats := make([]formatInfo, 0, len(best))
for h, f := range best {
formats = append(formats, formatInfo{ID: f.FormatID, Label: fmt.Sprintf("%dp", h), Height: h})
}
sort.Slice(formats, func(i, j int) bool { return formats[i].Height > formats[j].Height })
writeJSON(w, http.StatusOK, map[string]any{
"title": info.Title,
"thumbnail": info.Thumbnail,
"duration": info.Duration,
"uploader": info.Uploader,
"formats": formats,
// Which one the selected default resolution maps to, so the card can
// highlight it without knowing the rule.
"default_id": defaultFormatID(formats, getResolutionHeight()),
})
}
func handlePlaylist(w http.ResponseWriter, r *http.Request) {
var req struct {
URL string `json:"url"`
}
if err := readJSON(r, &req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request"})
return
}
req.URL = strings.TrimSpace(req.URL)
if req.URL == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "No URL provided"})
return
}
ctx, cancel := context.WithTimeout(context.Background(), infoTimeout)
defer cancel()
stdout, stderr, err := runCmd(ctx, "--flat-playlist", "-J", req.URL)
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Timed out fetching playlist info"})
return
}
writeJSON(w, http.StatusBadRequest, map[string]string{"error": cmdError(stderr, err)})
return
}
var info struct {
Entries []struct {
URL string `json:"url"`
} `json:"entries"`
}
if err := json.Unmarshal(stdout, &info); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
urls := make([]string, 0, len(info.Entries))