-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
84 lines (75 loc) · 1.85 KB
/
http.go
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
package main
import (
"bytes"
"log"
"net/http"
"os"
"strconv"
"time"
)
func GetYear(r *http.Request) int {
year, err := strconv.Atoi(r.URL.Query().Get("year"))
if err == nil {
return year
}
now := time.Now()
year = now.Year()
if now.Month() <= time.March {
year -= 1
}
return year
}
func FilterByTags(courses []Course, tags []string) []Course {
m := make(map[string]struct{}, len(tags))
for _, t := range tags {
m[t] = struct{}{}
}
filtered := make([]Course, 0, len(courses))
for _, c := range courses {
for _, t := range c.Tags {
if _, ok := m[t]; ok {
filtered = append(filtered, c)
break
}
}
}
return filtered
}
func ICSHandler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(os.Getenv("COOKIE_NAME"))
if err == http.ErrNoCookie {
http.Error(w, "authentication required", http.StatusUnauthorized)
return
}
if err != nil {
log.Printf("failed to get cookie: %+v", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
ctx := WithAPICookie(r.Context(), cookie.String())
year := GetYear(r)
modules, err := GetSchoolCalendar(ctx, year)
if err != nil {
log.Printf("failed to get school calendar: %+v", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
courses, err := GetCourses(ctx, year)
if err != nil {
log.Printf("failed to get courses: %+v", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
if r.URL.Query().Has("tags[]") {
tags := r.URL.Query()["tags[]"]
courses = FilterByTags(courses, tags)
}
var resp bytes.Buffer
WriteICalendar(&resp, modules, courses)
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.Itoa(resp.Len()))
_, err = resp.WriteTo(w)
if err != nil {
log.Printf("failed to write response: %+v", err)
}
}