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