uofgcal/main.go

93 lines
1.7 KiB
Go
Raw Normal View History

2024-10-24 14:31:10 +00:00
package main
import (
"encoding/base64"
"fmt"
"io"
"net/http"
"os"
2024-10-24 14:41:43 +00:00
"time"
2024-10-24 14:31:10 +00:00
"github.com/charmbracelet/log"
2024-10-24 14:41:43 +00:00
"github.com/go-co-op/gocron/v2"
2024-10-24 14:31:10 +00:00
)
const calendar_url = "https://frontdoor.spa.gla.ac.uk/spacett/download/uogtimetable.ics"
var authorization string
func main() {
// collect guid and password
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)
2024-10-24 14:41:43 +00:00
// create scheduler
s, err := gocron.NewScheduler()
if err != nil {
log.Fatal(err)
}
j, err := s.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()
s.Start()
// block until ready
time.Sleep(24 * time.Hour)
err = s.Shutdown()
2024-10-24 14:31:10 +00:00
if err != nil {
log.Fatal(err)
}
}