aplus/canvas.go

119 lines
2.7 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 := os.Getenv("CANVAS_INSTANCE")
if len(instance_url) == 0 {
fmt.Println("The CANVAS_INSTANCE environment variable seems to be empty. Exiting.")
os.Exit(1)
}
base_link = instance_url + "/api/v1"
token = os.Getenv("CANVAS_API_KEY")
if len(token) == 0 {
fmt.Println("The CANVAS_API_KEY environment variable seems to be empty. Exiting.")
os.Exit(1)
}
jar, _ := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
client = http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if verbose {
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 = tool.URL
external_tools_code = tool.ID
return nil
}
}
return errors.New("Could not find A+ link and tool ID")
}
func list_all_courses(onlyreturn bool) []CanvasCourse {
all_courses := fmt.Sprintf("%s/courses?access_token=%s&enrollment_state=active&per_page=100", base_link, token)
canvas_courses := get_courses(token, all_courses, client)
if !onlyreturn {
for _, course := range canvas_courses {
fmt.Printf("%d, %s\n", course.ID%10000, course.Name)
}
return nil
}
return canvas_courses
}
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)
}
}