summaryrefslogtreecommitdiff
path: root/grimtube.go
blob: 17de1b6521e23b77df9539caa36c968b5adb0298 (plain)
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package main

import (
	"flag"
	"text/template"
	"net/http"
	"fmt"
	//"io"
	"log"
	"strconv"
	//"path"

	"git.sr.ht/~ark/ytparser"
)

func getLangs() []string {
	return []string{"en", "fr", "de", "ja", "ru"}
}

func serve(w http.ResponseWriter, templatePath string, data interface{}) {
	funcMap := template.FuncMap {
		"inc": func(i int) int {
			return i + 1
		},
		"dec": func(i int) int {
			return i - 1
		},
	}
	t, err := template.New("base.html").Funcs(funcMap).ParseFiles("templates/base.html", templatePath)
	if err != nil {
		panic(err)
	} else {
		if err := t.Execute(w, data); err != nil {
			log.Println(err)
		}
	}
}

func index(w http.ResponseWriter, r *http.Request) {
	data := struct {
		Langs []string
	}{
		getLangs(),
	}
	serve(w, "templates/index.html", data)
}

func search(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		query := r.URL.Query()
		term := query.Get("term")
		sPage := query.Get("page")
		lang := query.Get("lang")
		var page int
		if sPage == "" {
			page = 0
		} else {
			p, err := strconv.Atoi(sPage)
			if err != nil {
				page = 0
			} else {
				page = p
			}
		}
		log.Printf("searching: %s, page: %d, lang: %s\n", term, page, lang)
		items, err := ytparser.Search(term, page, lang)
		if err != nil {
			log.Println(err)
			data := struct {
				Error error
			}{
				err,
			}
			serve(w, "templates/error.html", data)
		} else {
			data := struct {
				Items []ytparser.Item
				Term string
				Page int
				Lang string
				Langs []string
			}{
				items,
				term,
				page,
				lang,
				getLangs(),
			}
			serve(w, "templates/search.html", data)
		}
	default:
	}
}

func embed(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		query := r.URL.Query()
		id := query.Get("id")
		serve(w, "templates/embed.html", id)
	default:
	}
}

func favicon(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "favicon.ico")
}

func main() {
	port := flag.Int("p", 8080, "The port to bind to.")
	flag.Parse()
	fs := http.FileServer(http.Dir("static"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))
	http.HandleFunc("/favicon.ico", favicon)
	http.HandleFunc("/", index)
	http.HandleFunc("/search", search)
	http.HandleFunc("/embed", embed)

	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
}