-
Notifications
You must be signed in to change notification settings - Fork 1
/
fixyoutube.go
95 lines (83 loc) · 2.44 KB
/
fixyoutube.go
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
package main
import (
"net/http"
"os"
"strconv"
"time"
"github.com/BiRabittoh/fixyoutube-go/invidious"
"github.com/joho/godotenv"
"github.com/sirupsen/logrus"
"golang.org/x/time/rate"
)
var (
apiKey string
debugSwitch = false
logger = logrus.New()
)
func limit(limiter *rate.Limiter, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !limiter.Allow() {
status := http.StatusTooManyRequests
http.Error(w, http.StatusText(status), status)
return
}
next.ServeHTTP(w, r)
})
}
func getenvDefault(key string, def string) string {
res := os.Getenv(key)
if res == "" {
return def
}
return res
}
func getenvDefaultParse(key string, def string) float64 {
value := getenvDefault(key, def)
res, err := strconv.ParseFloat(value, 64)
if err != nil {
logger.Fatal(err)
}
return res
}
func main() {
err := godotenv.Load()
if err != nil {
logger.Info("No .env file provided.")
}
if os.Getenv("DEBUG") != "" {
logger.SetLevel(logrus.DebugLevel)
logger.Debug("Debug mode enabled (rate limiting is disabled)")
debugSwitch = true
}
apiKey = getenvDefault("API_KEY", "itsme")
port := getenvDefault("PORT", "3000")
burstTokens := getenvDefaultParse("BURST_TOKENS", "3")
rateLimit := getenvDefaultParse("RATE_LIMIT", "1")
cacheDuration := getenvDefaultParse("CACHE_DURATION_MINUTES", "5")
timeoutDuration := getenvDefaultParse("TIMEOUT_DURATION_MINUTES", "10")
cleanupInterval := getenvDefaultParse("CLEANUP_INTERVAL_SECONDS", "30")
maxSizeMB := getenvDefaultParse("MAX_SIZE_MB", "20")
myClient := &http.Client{Timeout: 10 * time.Second}
options := invidious.ClientOptions{
CacheDuration: time.Duration(cacheDuration) * time.Minute,
TimeoutDuration: time.Duration(timeoutDuration) * time.Minute,
CleanupInterval: time.Duration(cleanupInterval) * time.Second,
MaxSizeBytes: int64(maxSizeMB * 1000000),
}
videoapi := invidious.NewClient(myClient, options)
r := http.NewServeMux()
r.HandleFunc("/", indexHandler)
r.HandleFunc("/clear", clearHandler)
r.HandleFunc("/watch", watchHandler(videoapi))
r.HandleFunc("/proxy/{videoId}", proxyHandler(videoapi))
r.HandleFunc("/{videoId}", shortHandler(videoapi))
var serveMux http.Handler
if debugSwitch {
serveMux = r
} else {
limiter := rate.NewLimiter(rate.Limit(rateLimit), int(burstTokens))
serveMux = limit(limiter, r)
}
logger.Info("Serving on port ", port)
http.ListenAndServe(":"+port, serveMux)
}