-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
388 lines (316 loc) · 10.1 KB
/
main.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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package main
import (
"bytes"
"crypto/sha1"
"fmt"
"net/http"
"os"
"path"
"slices"
"strconv"
"strings"
"text/template"
"time"
"github.com/csunibo/unibo-go/curriculum"
"github.com/csunibo/unibo-go/timetable"
ics "github.com/arran4/golang-ical"
"github.com/gin-contrib/multitemplate"
limits "github.com/gin-contrib/size"
"github.com/gin-gonic/gin"
"github.com/lf4096/gin-compress"
"github.com/patrickmn/go-cache"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/VaiTon/unibocalendar/unibo_integ"
)
//go:generate pnpm run css:build
const templateDir = "./templates"
func createMyRender() multitemplate.Renderer {
funcMap := template.FuncMap{"anniRange": func(end int) []int {
r := make([]int, 0, end)
for i := 1; i <= end; i++ {
r = append(r, i)
}
return r
}}
r := multitemplate.NewRenderer()
r.AddFromFiles("base", path.Join(templateDir, "base.gohtml"))
r.AddFromFilesFuncs("index", funcMap,
path.Join(templateDir, "index.gohtml"), path.Join(templateDir, "base.gohtml"),
)
r.AddFromFilesFuncs("courses", funcMap,
path.Join(templateDir, "courses.gohtml"), path.Join(templateDir, "base.gohtml"),
)
r.AddFromFilesFuncs("course", funcMap,
path.Join(templateDir, "course.gohtml"), path.Join(templateDir, "base.gohtml"),
)
return r
}
func main() {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
downloadOpenDataIfNewer()
courses, err := openData()
if err != nil {
log.Fatal().Err(err).Msg("Unable to open open data file")
}
go fillSubjectsCache(courses)
r := setupRouter(courses)
err = r.Run()
if err != nil {
log.Fatal().Err(err).Msg("Unable to start server")
}
}
func setupRouter(courses unibo_integ.CoursesMap) *gin.Engine {
r := gin.Default()
r.Use(compress.Compress())
// Limit payload to 10 MB. This fixes zip bombs.
r.Use(limits.RequestSizeLimiter(10 * 1024 * 1024))
r.HTMLRender = createMyRender()
r.Static("/static", "./static")
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index", gin.H{})
})
coursesList := courses.ToList()
slices.SortFunc(coursesList, func(a, b unibo_integ.Course) int {
return b.Codice - a.Codice
})
r.GET("/courses", func(c *gin.Context) {
c.HTML(http.StatusOK, "courses", gin.H{
"courses": coursesList,
})
})
r.GET("/courses/:id", coursePage(courses))
r.GET("/cal/:id/:anno", getCoursesCal(&courses))
return r
}
func coursePage(courses unibo_integ.CoursesMap) func(c *gin.Context) {
return func(ctx *gin.Context) {
courseId := ctx.Param("id")
if courseId == "" {
ctx.String(http.StatusBadRequest, "Invalid course id")
return
}
courseIdInt, err := strconv.Atoi(courseId)
if err != nil {
ctx.String(http.StatusBadRequest, "Invalid course id")
return
}
course, found := courses.FindById(courseIdInt)
if !found {
ctx.String(http.StatusNotFound, "Course not found")
return
}
curricula, err := course.GetAllCurricula()
if err != nil {
_ = ctx.Error(fmt.Errorf("unable to retrieve curricula: %w", err))
curricula = nil
}
m, err := getSubjectsMapFromCourseAndCurricula(course, curricula)
if err != nil {
_ = ctx.Error(fmt.Errorf("unable to retrieve subjects: %w", err))
}
ctx.HTML(http.StatusOK, "course", gin.H{
"Course": course,
"Curricula": curricula,
"Teachings": m,
})
}
}
var calcache = cache.New(time.Minute*10, time.Minute*30)
func getCoursesCal(courses *unibo_integ.CoursesMap) func(c *gin.Context) {
return func(ctx *gin.Context) {
id := ctx.Param("id")
anno := ctx.Param("anno")
// Check if id is a number, otherwise return 400
annoInt, err := strconv.Atoi(anno)
if err != nil {
ctx.String(http.StatusBadRequest, "Invalid year")
return
}
// Check if id is a number, otherwise return 400
idInt, err := strconv.Atoi(id)
if err != nil {
ctx.String(http.StatusBadRequest, "Invalid id")
return
}
// Check if course exists, otherwise return 404
course, found := courses.FindById(idInt)
if !found {
ctx.String(http.StatusNotFound, "Course not found")
return
}
if annoInt <= 0 || annoInt > course.DurataAnni {
ctx.String(http.StatusBadRequest, "Invalid year")
return
}
curriculumId := ctx.Query("curr")
curr := curriculum.Curriculum{}
if curriculumId != "" {
curr.Value = curriculumId
}
subjectIds := ctx.Query("subjects")
var subjects []string
if subjectIds != "" {
tmp := strings.Split(subjectIds, ",")
for i := range tmp {
if len(tmp[i]) != 0 {
subjects = append(subjects, tmp[i])
}
}
log.Debug().Strs("subjects", subjects).Msg("queried subjects")
}
slices.Sort(subjects)
cacheKey := fmt.Sprintf("%s-%s-%s-%s", id, anno, curr.Value, subjects)
if cal, found := calcache.Get(cacheKey); found {
successCalendar(ctx, cal.(*bytes.Buffer))
return
}
// Try to retrieve timetable, otherwise return 500
courseTimetable, err := course.GetTimetable(annoInt, curr, nil)
if err != nil {
_ = ctx.Error(err)
ctx.String(http.StatusInternalServerError, "Unable to retrieve timetable")
return
}
cal, err := createCal(courseTimetable, course, annoInt, subjects)
if err != nil {
_ = ctx.Error(err)
ctx.String(http.StatusInternalServerError, "Unable to create calendar")
return
}
buf := bytes.NewBuffer(nil)
err = cal.SerializeTo(buf)
if err != nil {
_ = ctx.Error(err)
ctx.String(http.StatusInternalServerError, "Unable to serialize calendar")
return
}
calcache.Set(cacheKey, buf, cache.DefaultExpiration)
successCalendar(ctx, buf)
}
}
func successCalendar(c *gin.Context, cal *bytes.Buffer) {
c.Header("Content-Type", "text/calendar; charset=utf-8")
c.Header("Content-Disposition", "attachment; filename=lezioni.ics")
// Allow CORS
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, Authorization")
c.Header("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS")
c.String(http.StatusOK, cal.String())
}
// createCal creates a calendar from the given timetable.
//
// If subjectCodes is not nil, it will be used to filter the timetable by subjects.
func createCal(
timetable timetable.Timetable,
course *unibo_integ.Course,
year int,
subjectCodes []string,
) (*ics.Calendar, error) {
// Filter timetable by subjects
if subjectCodes != nil {
timetable = filterTimetableBySubjects(timetable, subjectCodes)
}
cal := ics.NewCalendar()
cal.SetMethod(ics.MethodRequest)
for _, event := range timetable {
sha := sha1.New()
_, err := sha.Write([]byte(fmt.Sprintf("%s%s%s", event.CodModulo, event.Start, event.End)))
if err != nil {
return nil, err
}
eventUid := fmt.Sprintf("%x", sha.Sum(nil))
e := cal.AddEvent(eventUid)
e.SetOrganizer(event.Teacher)
e.SetSummary(event.Title)
e.SetStartAt(event.Start.Time)
e.SetEndAt(event.End.Time)
e.SetDtStampTime(time.Now()) // https://www.kanzaki.com/docs/ical/dtstamp.html
b := strings.Builder{}
b.WriteString(fmt.Sprintf("Docente: %s\n", event.Teacher))
if len(event.Classrooms) > 0 {
classroom := event.Classrooms[0]
b.WriteString(fmt.Sprintf("Aula: %s\n", classroom.ResourceDesc))
e.SetLocation(classroom.ResourceDesc)
}
b.WriteString(fmt.Sprintf("Cfu: %d\n", event.Cfu))
b.WriteString(fmt.Sprintf("Periodo: %s\n", event.Interval))
b.WriteString(fmt.Sprintf("Codice modulo: %s\n", event.CodModulo))
e.SetDescription(b.String())
}
calName := fmt.Sprintf("%s - %d year", course.Descrizione, year)
cal.SetName(calName)
calDesc := fmt.Sprintf("Orario delle lezioni del %d anno del corso di %s",
year, course.Descrizione)
cal.SetDescription(calDesc)
return cal, nil
}
func filterTimetableBySubjects(t timetable.Timetable, codes []string) timetable.Timetable {
filtered := make([]timetable.Event, 0, len(t))
for _, event := range t {
if slices.Contains(codes, event.CodModulo) {
filtered = append(filtered, event)
}
}
return filtered
}
var (
subjectsCacheExpirationTime = time.Hour * 4
subjectsCache = cache.New(subjectsCacheExpirationTime, time.Hour*6)
)
type subjectMap = map[int]map[curriculum.Curriculum][]timetable.SimpleSubject
// The return type is a map that for every year of the course map a curriculum
// to a slice of subjects
func getSubjectsMapFromCourseAndCurricula(course *unibo_integ.Course, curricula map[int]curriculum.Curricula) (subjectMap, error) {
if course == nil {
return nil, fmt.Errorf("course parameter is nil")
}
// To get a curricula from a course we need fetch from the unibo API. Sometimes
// this could fail, so the curricula is nil. We need to check to avoid crashing
// the program.
if curricula == nil {
return nil, fmt.Errorf("curricula parameter is nil")
}
m := make(subjectMap)
for y, cs := range curricula {
m[y] = make(map[curriculum.Curriculum][]timetable.SimpleSubject)
for _, c := range cs {
var subjects []timetable.SimpleSubject
key := fmt.Sprintf("%d-%d-%s", course.Codice, y, c.Value)
if t, found := subjectsCache.Get(key); found {
m[y][c] = t.([]timetable.SimpleSubject)
continue
}
courseTimetable, err := course.GetTimetable(y, c, nil)
if err != nil {
// Can't do much. We return nil so the caller can retry
return nil, fmt.Errorf("unable to retrieve timetable for subjects: %w", err)
}
subjects = courseTimetable.GetSubjects()
subjectsCache.Set(key, subjects, cache.DefaultExpiration)
m[y][c] = subjects
}
}
return m, nil
}
// This functions calls getSubjectsMapFromCourseAndCurricula for every course,
// so the cache is always full and users do not see a slow site
func fillSubjectsCache(courses unibo_integ.CoursesMap) {
// This is to make sure everything is started
time.Sleep(time.Second * 5)
for _, course := range courses {
log.Debug().Int("course-code", course.Codice).Str("course-name", course.Descrizione).Msg("queried subjects")
curricula, err := course.GetAllCurricula()
if err != nil {
log.Err(err).Int("course-code", course.Codice).Str("course-name", course.Descrizione).Msg("Can't get curricula in workerfor course")
continue
}
_, err = getSubjectsMapFromCourseAndCurricula(&course, curricula)
if err != nil {
log.Err(err).Msg("Can't subjects in worker")
continue
}
time.Sleep(time.Second * 30)
}
time.Sleep(subjectsCacheExpirationTime)
}