92 lines
1.7 KiB
Go
92 lines
1.7 KiB
Go
package main
|
|
|
|
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
|
|
|
|
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)
|
|
|
|
// 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()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|