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