all repos — gopipe @ d9ab51a35a4242ee8f1f5c0760ced3905f84e872

Embed YouTube videos on Telegram, Discord and more!

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	data := map[string]interface{}{
66		"VideoID":     videoID,
67		"VideoURL":    format.URL,
68		"Uploader":    video.Author,
69		"Title":       video.Title,
70		"Description": video.Description,
71		"Duration":    video.Duration,
72		"Debug":       g.Debug,
73	}
74
75	err = templates.ExecuteTemplate(w, "video.html", data)
76	if err != nil {
77		log.Println("indexHandler ERROR: ", err)
78		http.Error(w, err500, http.StatusInternalServerError)
79		return
80	}
81}