aplus/canvas.go
2023-11-20 10:08:58 -05:00

99 lines
2.3 KiB
Go

package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"os"
"strings"
"golang.org/x/net/publicsuffix"
)
func initialize() {
instance_url := "https://floridapolytechnic.instructure.com"
base_link = instance_url + "/api/v1"
token = os.Getenv("CANVAS_API_KEY")
jar, _ := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
client = http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
fmt.Println("Redirected to:", req.URL)
fmt.Println(req.Cookies())
return nil
},
Jar: jar,
}
}
func get_courses(token string, link string, client http.Client) []CanvasCourse {
resp, err := client.Get(link)
if err != nil {
fmt.Println("Error performing GET request to get courses.")
return nil
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var canvas_courses []CanvasCourse
err2 := json.Unmarshal(body, &canvas_courses)
if err2 != nil {
fmt.Println(err2)
return nil
}
return canvas_courses
}
func init_aplus_toolid(course_id int) error {
link := fmt.Sprintf("%s/courses/%d/external_tools?access_token=%s&search_term=aplus&include_parents=true", base_link, course_id, token)
resp, err := client.Get(link)
if err != nil {
return err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var external_tools []ExternalTool
err = json.Unmarshal(body, &external_tools)
if err != nil && !strings.Contains(string(body), "\"unauthorized\"") {
return err
}
for _, tool := range external_tools {
if strings.Contains(tool.URL, ".aplusattendance.com/") && base_aplus_link == "" {
base_aplus_link = tool.URL
external_tools_code = tool.ID
}
}
return errors.New("Could not find A+ link and tool ID")
}
func list_all_courses() {
all_courses := fmt.Sprintf("%s/courses?access_token=%s&per_page=100", base_link, token)
canvas_courses := get_courses(token, all_courses, client)
for _, course := range canvas_courses {
fmt.Printf("%d, %s\n", course.ID%10000, course.Name)
}
}
func list_favorite_courses() {
// course selection by user happens below
favorites := fmt.Sprintf("%s/users/self/favorites/courses?access_token=%s&per_page=100", base_link, token)
canvas_courses := get_courses(token, favorites, client)
for _, course := range canvas_courses {
fmt.Printf("%d, %s\n", course.ID%10000, course.Name)
}
}