src/app/handlers.go (view raw)
1package app
2
3import (
4 "log"
5 "net/http"
6 "regexp"
7 "strconv"
8 "text/template"
9 "time"
10
11 g "github.com/birabittoh/gopipe/src/globals"
12)
13
14const (
15 fmtYouTubeURL = "https://www.youtube.com/watch?v=%s"
16 err500 = "Internal Server Error"
17 urlDuration = 6 * time.Hour
18)
19
20var (
21 templates = template.Must(template.ParseGlob("templates/*.html"))
22 userAgentRegex = regexp.MustCompile(`(?i)bot|facebook|embed|got|firefox\/92|firefox\/38|curl|wget|go-http|yahoo|generator|whatsapp|preview|link|proxy|vkshare|images|analyzer|index|crawl|spider|python|cfnetwork|node`)
23 videoRegex = regexp.MustCompile(`(?i)^[a-z0-9_-]{11}$`)
24)
25
26func indexHandler(w http.ResponseWriter, r *http.Request) {
27 err := templates.ExecuteTemplate(w, "index.html", nil)
28 if err != nil {
29 log.Println("indexHandler ERROR: ", err)
30 http.Error(w, err500, http.StatusInternalServerError)
31 return
32 }
33}
34
35func videoHandler(w http.ResponseWriter, r *http.Request) {
36 videoID := r.URL.Query().Get("v")
37 if videoID == "" {
38 videoID = r.PathValue("videoID")
39 if videoID == "" {
40 http.Error(w, "Missing video ID", http.StatusBadRequest)
41 return
42 }
43 }
44
45 if !userAgentRegex.MatchString(r.UserAgent()) {
46 log.Println("Regex did not match. UA: ", r.UserAgent())
47 if !g.Debug {
48 log.Println("Redirecting.")
49 http.Redirect(w, r, getURL(videoID), http.StatusFound)
50 return
51 }
52 }
53
54 if !videoRegex.MatchString(videoID) {
55 log.Println("Invalid video ID: ", videoID)
56 http.Error(w, "Invalid video ID.", http.StatusBadRequest)
57 return
58 }
59
60 formatID, err := strconv.ParseUint(r.PathValue("formatID"), 10, 64)
61 if err != nil {
62 formatID = 0
63 }
64
65 video, format, err := getVideo(videoID, int(formatID))
66 if err != nil {
67 http.Error(w, err500, http.StatusInternalServerError)
68 return
69 }
70
71 if video == nil || format == nil {
72 http.Error(w, err500, http.StatusInternalServerError)
73 return
74 }
75
76 data := map[string]interface{}{
77 "VideoID": videoID,
78 "VideoURL": format.URL,
79 "Uploader": video.Author,
80 "Title": video.Title,
81 "Description": video.Description,
82 "Duration": video.Duration,
83 "Debug": g.Debug,
84 }
85
86 err = templates.ExecuteTemplate(w, "video.html", data)
87 if err != nil {
88 log.Println("indexHandler ERROR: ", err)
89 http.Error(w, err500, http.StatusInternalServerError)
90 return
91 }
92}