uofgcal/fetch/fetch.go
2024-10-24 15:54:51 +01:00

86 lines
1.6 KiB
Go

package fetch
import (
"encoding/base64"
"fmt"
"io"
"net/http"
"os"
"time"
"github.com/charmbracelet/log"
"github.com/go-co-op/gocron/v2"
)
const calendar_url = "https://frontdoor.spa.gla.ac.uk/spacett/download/uogtimetable.ics"
var authorization string
var Scheduler *gocron.Scheduler
func CollectAuth() {
var (
guid string
password string
)
fmt.Print("Enter your GUID: ")
fmt.Scan(&guid)
fmt.Print("Enter your password: ")
fmt.Scan(&password)
b64 := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", guid, password)))
authorization = fmt.Sprintf("Basic %s", b64)
}
func StartScheduler() {
// create scheduler
Scheduler, err := gocron.NewScheduler()
if err != nil {
log.Fatal(err)
}
j, err := Scheduler.NewJob(
// every 24 hours
gocron.DurationJob(
24*time.Hour,
),
// fetch the calendar
gocron.NewTask(
func() {
// create request
req, err := http.NewRequest("GET", calendar_url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", authorization)
// send request
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// read response
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// check if authentication failed
if resp.StatusCode == 401 {
log.Fatal("authentication failed")
} else {
os.WriteFile("calendar.ics", body, 0644)
log.Info("Written calendar to calendar.ics")
}
},
),
)
if err != nil {
log.Fatal(err)
}
// run job and start scheduler
go j.RunNow()
Scheduler.Start()
}