canvas

package module
v0.0.0-...-14ec235 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 29, 2023 License: Apache-2.0 Imports: 19 Imported by: 0

README

go-canvas

An API client for Instructure's Canvas API.

Build Status GoDoc Go Report Card codecov TODOs

Download/Install

go get github.com/harrybrwn/go-canvas

Getting Started

  1. Get a token from your canvas account, this should help.
  2. Give the token to the library
    • Set $CANVAS_TOKEN environment variable
    • Call canvas.SetToken or canvas.New
  3. For more advance usage, viewing the canvas API docs and using the canvas.Option interface will be usful for more fine-tuned api use.
Concurrent Error Handling

Error handling for functions that return a channel and no error is done with a callback. This callback is called ConcurrentErrorHandler and in some cases, a struct may have a SetErrorHandler function.

canvas.ConcurrentErrorHandler = func(e error) error {
    if canvas.IsRateLimit(e) {
        fmt.Println("rate limit reached")
        return nil
    }
    return e
}
for f := range canvas.Files() {
    fmt.Println(f.Filename, f.ID)
}

TODO

  • Groups
  • Outcome Groups
  • Favorites
  • Submissions
    • submiting assignments
    • file upload on assginments

Documentation

Overview

Package canvas is an API wrapper for Instructure's Canvas API written in Go.

For the official Canvas API documentation, see https://canvas.instructure.com/doc/api/all_resources.html

Example (ConcurrentErrorHandling)
var (
	failed bool
	err    error
)
canvas.SetToken("bad token")
reset := canvas.ConcurrentErrorHandler
canvas.ConcurrentErrorHandler = func(e error) error {
	if _, ok := e.(*canvas.Error); !ok {
		failed = true
		err = e
		return e // non-nil will stop all goroutines
	}
	return nil // nil means we want to continue
}

count := 0
for file := range canvas.Files() {
	if failed {
		// log.Fatal(err)
		break
	}
	if file != nil {
		count++
	}
}
canvas.ConcurrentErrorHandler = reset
fmt.Println(err)
fmt.Println(failed)
Output:

Invalid access token.
true

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// DefaultHost is the default url host for the canvas api.
	DefaultHost = "canvas.instructure.com"

	// ConcurrentErrorHandler is the error handling callback for
	// handling errors in tricky goroutines.
	//
	// If you do not want to stop all concurrent goroutines, this
	// handler should return an non-nil error. If this handler returns
	// nil then all goroutines will continue if they can.
	// This function panics by default.
	ConcurrentErrorHandler func(error) error = defaultErrorHandler

	// DefaultUserAgent is the default user agent used to make requests.
	DefaultUserAgent = "go-canvas v0.1"
)
View Source
var (
	// ErrRateLimitExceeded is returned when the api rate limit has been reached.
	ErrRateLimitExceeded = errors.New("403 Forbidden (Rate Limit Exceeded)")
)

Functions

func CoursesChan

func CoursesChan(opts ...Option) <-chan *Course

CoursesChan returns a channel of courses

func CreateBookmark

func CreateBookmark(b *Bookmark) error

CreateBookmark will take a bookmark and send it to canvas.

func DeleteBookmark

func DeleteBookmark(b *Bookmark) error

DeleteBookmark will delete a bookmark

func Files

func Files(opts ...Option) <-chan *File

Files will return a channel of all the default user's files. https://canvas.instructure.com/doc/api/files.html#method.files.api_index

func Folders

func Folders(opts ...Option) <-chan *Folder

Folders returns a channel of folders for the current user.

func IsRateLimit

func IsRateLimit(e error) bool

IsRateLimit returns true if the error given is a rate limit error.

func JoinFileObjs

func JoinFileObjs(files <-chan *File, folders <-chan *Folder) <-chan FileObj

JoinFileObjs will join a file channel and a folder channel into a generic file objects channel.

func SetHost

func SetHost(host string) error

SetHost will set the package level host.

func SetToken

func SetToken(token string)

SetToken will set the package level canvas object token.

func UpdateCalendarEvent

func UpdateCalendarEvent(event *CalendarEvent) error

UpdateCalendarEvent will update a calendar event. This operation will change event given as an argument. https://canvas.instructure.com/doc/api/all_resources.html#method.calendar_events_api.update

Types

type Account

type Account struct {
	ID              int    `json:"id"`
	Name            string `json:"name"`
	UUID            string `json:"uuid"`
	ParentAccountID int    `json:"parent_account_id"`
	RootAccountID   int    `json:"root_account_id"`
	WorkflowState   string `json:"workflow_state"`
	DefaultTimeZone string `json:"default_time_zone"`
	IntegrationID   string `json:"integration_id"`
	SisAccountID    string `json:"sis_account_id"`
	SisImportID     int    `json:"sis_import_id"`
	LtiGUID         string `json:"lti_guid"`

	// Storage Quotas
	DefaultStorageQuotaMB      int `json:"default_storage_quota_mb"`
	DefaultUserStorageQuotaMB  int `json:"default_user_storage_quota_mb"`
	DefaultGroupStorageQuotaMB int `json:"default_group_storage_quota_mb"`

	Domain   string      `json:"domain"`
	Distance interface{} `json:"distance"`
	// Authentication Provider
	AuthProvider string `json:"authentication_provider"`
	// contains filtered or unexported fields
}

Account is an account

func Accounts

func Accounts(opts ...Option) ([]Account, error)

Accounts will list the accounts

func CourseAccounts

func CourseAccounts(opts ...Option) ([]Account, error)

CourseAccounts will make a call to the course accounts endpoint

func CurrentAccount

func CurrentAccount() (a *Account, err error)

CurrentAccount will get the current account.

func SearchAccounts

func SearchAccounts(term string, opts ...Option) ([]Account, error)

SearchAccounts will search for canvas accounts. Options: name, domain, latitude, longitude

func (*Account) Courses

func (a *Account) Courses(opts ...Option) (courses []*Course, err error)

Courses returns the account's list of courses

type Assignment

type Assignment struct {
	Name        string `json:"name" url:"name,omitempty"`
	Description string `json:"description" url:"description,omitempty"`
	ID          int    `json:"id" url:"-"`

	DueAt     time.Time `json:"due_at" url:"due_at,omitempty"`
	LockAt    time.Time `json:"lock_at" url:"lock_at,omitempty"`
	UnlockAt  time.Time `json:"unlock_at" url:"unlock_at,omitempty"`
	CreatedAt time.Time `json:"created_at" url:"-"`
	UpdatedAt time.Time `json:"updated_at" url:"-"`

	Overrides              []AssignmentOverride `json:"overrides" url:"assignment_overrides,brackets,omitempty"`
	OnlyVisibleToOverrides bool                 `json:"only_visible_to_overrides" url:"only_visible_to_overrides,omitempty"`
	HasOverrides           bool                 `json:"has_overrides" url:"-"`

	AssignmentGroupID              int               `json:"assignment_group_id" url:"assignment_group_id,omitempty"`
	AllowedExtensions              []string          `json:"allowed_extensions" url:"allowed_extensions,brackets,omitempty"`
	TurnitinEnabled                bool              `json:"turnitin_enabled" url:"turnitin_enabled,omitempty"`
	VericiteEnabled                bool              `json:"vericite_enabled" url:"vericite_enabled,omitempty"`
	TurnitinSettings               *TurnitinSettings `json:"turnitin_settings" url:"turnitin_settings,omitempty"`
	GradeGroupStudentsIndividually bool              `json:"grade_group_students_individually" url:"grade_group_students_individually,omitempty"`
	ExternalToolTagAttributes      interface{}       `json:"external_tool_tag_attributes" url:"external_tool_tag_attributes,omitempty"`
	PeerReviews                    bool              `json:"peer_reviews" url:"peer_reviews,omitempty"`
	AutomaticPeerReviews           bool              `json:"automatic_peer_reviews" url:"automatic_peer_reviews,omitempty"`
	GroupCategoryID                int               `json:"group_category_id" url:"group_category_id,omitempty"`
	Position                       int               `json:"position" url:"position,omitempty"`
	IntegrationID                  string            `json:"integration_id" url:"integration_id,omitempty"`
	IntegrationData                map[string]string `json:"integration_data" url:"integration_data,omitempty"`
	NotifyOfUpdate                 bool              `json:"notify_of_update,omitempty" url:"notify_of_update,omitempty"`
	PointsPossible                 float64           `json:"points_possible" url:"points_possible,omitempty"`
	SubmissionTypes                []string          `json:"submission_types" url:"submission_types,brakets,omitempty"`
	GradingType                    GradingType       `json:"grading_type" url:"grading_type,omitempty"`
	GradingStandardID              interface{}       `json:"grading_standard_id" url:"grading_standard_id,omitempty"`
	Published                      bool              `json:"published" url:"published,omitempty"`
	SisAssignmentID                string            `json:"sis_assignment_id" url:"sis_assignment_id,omitempty"`

	PeerReviewCount            int         `json:"peer_review_count" url:"-"`
	AllDates                   interface{} `json:"all_dates" url:"-"`
	CourseID                   int         `json:"course_id" url:"-"`
	HTMLURL                    string      `json:"html_url" url:"-"`
	SubmissionsDownloadURL     string      `json:"submissions_download_url" url:"-"`
	DueDateRequired            bool        `json:"due_date_required" url:"-"`
	MaxNameLength              int         `json:"max_name_length" url:"-"`
	PeerReviewsAssignAt        time.Time   `json:"peer_reviews_assign_at" url:"-"`
	IntraGroupPeerReviews      bool        `json:"intra_group_peer_reviews" url:"-"`
	NeedsGradingCount          int         `json:"needs_grading_count" url:"-"`
	NeedsGradingCountBySection []struct {
		SectionID         string `json:"section_id" url:"-"`
		NeedsGradingCount int    `json:"needs_grading_count" url:"-"`
	} `json:"needs_grading_count_by_section" url:"-"`
	PostToSis               bool             `json:"post_to_sis" url:"-"`
	HasSubmittedSubmissions bool             `json:"has_submitted_submissions" url:"-"`
	Unpublishable           bool             `json:"unpublishable" url:"-"`
	LockedForUser           bool             `json:"locked_for_user" url:"-"`
	LockInfo                *LockInfo        `json:"lock_info" url:"-"`
	LockExplanation         string           `json:"lock_explanation" url:"-"`
	QuizID                  int              `json:"quiz_id" url:"-"`
	AnonymousSubmissions    bool             `json:"anonymous_submissions" url:"-"`
	DiscussionTopic         *DiscussionTopic `json:"discussion_topic" url:"-"`
	FreezeOnCopy            bool             `json:"freeze_on_copy" url:"-"`
	Frozen                  bool             `json:"frozen" url:"-"`
	FrozenAttributes        []string         `json:"frozen_attributes" url:"-"`
	Submission              *Submission      `json:"submission" url:"-"`
	UseRubricForGrading     bool             `json:"use_rubric_for_grading" url:"-"`
	RubricSettings          interface{}      `json:"rubric_settings" url:"-"`
	Rubric                  []RubricCriteria `json:"rubric" url:"-"`
	AssignmentVisibility    []int            `json:"assignment_visibility" url:"-"`
	PostManually            bool             `json:"post_manually" url:"-"`

	OmitFromFinalGrade              bool `json:"omit_from_final_grade" url:"omit_from_final_grade,omitempty"`
	ModeratedGrading                bool `json:"moderated_grading" url:"moderated_grading,omitempty"`
	GraderCount                     int  `json:"grader_count" url:"grader_count,omitempty"`
	FinalGraderID                   int  `json:"final_grader_id" url:"final_grader_id,omitempty"`
	GraderCommentsVisibleToGraders  bool `json:"grader_comments_visible_to_graders" url:"grader_comments_visible_to_graders,omitempty"`
	GradersAnonymousToGraders       bool `json:"graders_anonymous_to_graders" url:"graders_anonymous_to_graders,omitempty"`
	GraderNamesVisibleToFinalGrader bool `json:"grader_names_visible_to_final_grader" url:"graders_names_visible_to_final_grader,omitempty"`
	AnonymousGrading                bool `json:"anonymous_grading" url:"anonymous_grading,omitempty"`
	AllowedAttempts                 int  `json:"allowed_attempts" url:"allowed_attempts,omitempty"`
	// contains filtered or unexported fields
}

Assignment is a struct holding assignment data

func (*Assignment) SubmitFile

func (a *Assignment) SubmitFile(filename string, r io.Reader, opts ...Option) (*File, error)

SubmitFile will submit the contents of an io.Reader as a file to the assignment.

https://canvas.instructure.com/doc/api/submissions.html#method.submissions.create

func (*Assignment) SubmitOsFile

func (a *Assignment) SubmitOsFile(f *os.File) (*File, error)

SubmitOsFile is the same as SubmitFile except it takes advantage of the extra file data stored in an *os.File.

type AssignmentOverride

type AssignmentOverride struct {
	ID              int       `json:"id" url:"-"`
	Title           string    `json:"title" url:"title"`
	StudentIds      []int     `json:"student_ids" url:"student_ids,brackets,omitempty"`
	CourseSectionID int       `json:"course_section_id" url:"course_section_id"`
	DueAt           time.Time `json:"due_at" url:"due_at,omitempty"`
	UnlockAt        time.Time `json:"unlock_at" url:"unlock_at,omitempty"`
	LockAt          time.Time `json:"lock_at" url:"lock_at,omitempty"`

	AssignmentID int       `json:"assignment_id" url:"-"`
	GroupID      int       `json:"group_id" url:"-"`
	AllDay       bool      `json:"all_day" url:"-"`
	AllDayDate   time.Time `json:"all_day_date" url:"-"`
}

AssignmentOverride is an assignment override object

type AuthError

type AuthError struct {
	Status string     `json:"status"`
	Errors []errorMsg `json:"errors"`
}

AuthError is an authentication error response from canvas.

func (*AuthError) Error

func (ae *AuthError) Error() string

type Avatar

type Avatar struct {
	ID          int    `json:"id"`
	Type        string `json:"type"`
	DisplayName string `json:"display_name"`
	Filename    string `json:"filename"`
	URL         string `json:"url"`
	Token       string `json:"token"`
	ContentType string `json:"content-type"`
	Size        int    `json:"size"`
}

Avatar is the avatar data for a user.

type Bookmark

type Bookmark struct {
	ID       int    `json:"id"`
	Name     string `json:"name"`
	URL      string `json:"url"`
	Position int    `json:"position"`
	Data     struct {
		ActiveTab int `json:"active_tab"`
	} `json:"data"`
}

Bookmark is a bookmark object.

func Bookmarks

func Bookmarks(opts ...Option) ([]Bookmark, error)

Bookmarks will get the current user's bookmarks.

type CalendarEvent

type CalendarEvent struct {
	ID                         int         `json:"id" url:"-"`
	Title                      string      `json:"title" url:"title,omitempty"`
	ContextCode                string      `json:"context_code" url:"context_code,omitempty"`
	StartAt                    time.Time   `json:"start_at" url:"start_at,omitempty"`
	EndAt                      time.Time   `json:"end_at" url:"end_at,omitempty"`
	CreatedAt                  time.Time   `json:"created_at" url:"-"`
	UpdatedAt                  time.Time   `json:"updated_at" url:"-"`
	Description                string      `json:"description" url:"description,omitempty"`
	LocationName               string      `json:"location_name" url:"location_name,omitempty"`
	LocationAddress            string      `json:"location_address" url:"location_address,omitempty"`
	EffectiveContextCode       interface{} `json:"effective_context_code" url:"effective_context_code,omitempty"`
	AllDay                     bool        `json:"all_day" url:"all_day,omitempty"`
	AllContextCodes            string      `json:"all_context_codes" url:"-"`
	WorkflowState              string      `json:"workflow_state" url:"-"`
	Hidden                     bool        `json:"hidden" url:"-"`
	ParentEventID              interface{} `json:"parent_event_id" url:"-"`
	ChildEventsCount           int         `json:"child_events_count" url:"-"`
	ChildEvents                interface{} `json:"child_events" url:"-"`
	URL                        string      `json:"url" url:"-"`
	HTMLURL                    string      `json:"html_url" url:"-"`
	AllDayDate                 string      `json:"all_day_date" url:"-"`
	AppointmentGroupID         interface{} `json:"appointment_group_id" url:"-"`
	AppointmentGroupURL        string      `json:"appointment_group_url" url:"-"`
	OwnReservation             bool        `json:"own_reservation" url:"-"`
	ReserveURL                 string      `json:"reserve_url" url:"-"`
	Reserved                   bool        `json:"reserved" url:"-"`
	ParticipantType            string      `json:"participant_type" url:"-"`
	ParticipantsPerAppointment interface{} `json:"participants_per_appointment" url:"-"`
	AvailableSlots             interface{} `json:"available_slots" url:"-"`
	User                       *User       `json:"user" url:"-"`
	Group                      interface{} `json:"group" url:"-"`
}

CalendarEvent is a calendar event

func CalendarEvents

func CalendarEvents(opts ...Option) ([]*CalendarEvent, error)

CalendarEvents makes a call to get calendar events.

func CreateCalendarEvent

func CreateCalendarEvent(event *CalendarEvent) (*CalendarEvent, error)

CreateCalendarEvent will send a calendar event to canvas to be created. https://canvas.instructure.com/doc/api/all_resources.html#method.calendar_events_api.create

func DeleteCalendarEvent

func DeleteCalendarEvent(e *CalendarEvent) (*CalendarEvent, error)

DeleteCalendarEvent will delete the calendar event and return the calendar event deleted.

func DeleteCalendarEventByID

func DeleteCalendarEventByID(id int, opts ...Option) (*CalendarEvent, error)

DeleteCalendarEventByID will delete a calendar event given its ID. This operation returns the calendar event that was deleted.

type Canvas

type Canvas struct {
	// contains filtered or unexported fields
}

Canvas is the main api entry point.

func New

func New(token string) *Canvas

New will create a Canvas struct from an api token. New uses the default host.

func WithHost

func WithHost(token, host string) *Canvas

WithHost will create a canvas object that uses a different hostname.

func (*Canvas) Accounts

func (c *Canvas) Accounts(opts ...Option) ([]Account, error)

Accounts will list the accounts

func (*Canvas) Announcements

func (c *Canvas) Announcements(
	contextCodes []string,
	opts ...Option,
) (arr []*DiscussionTopic, err error)

Announcements will get the announcements https://canvas.instructure.com/doc/api/all_resources.html#method.announcements_api.index

func (*Canvas) Bookmarks

func (c *Canvas) Bookmarks(opts ...Option) (b []Bookmark, err error)

Bookmarks will get the current user's bookmarks.

func (*Canvas) CalendarEvents

func (c *Canvas) CalendarEvents(opts ...Option) (cal []*CalendarEvent, err error)

CalendarEvents makes a call to get calendar events.

func (*Canvas) Conversations

func (c *Canvas) Conversations(opts ...Option) (conversations []Conversation, err error)

Conversations returns a list of conversations

func (*Canvas) CourseAccounts

func (c *Canvas) CourseAccounts(opts ...Option) ([]Account, error)

CourseAccounts will make a call to the course accounts endpoint

func (*Canvas) Courses

func (c *Canvas) Courses(opts ...Option) ([]*Course, error)

Courses lists all of the courses associated with that canvas object.

https://canvas.instructure.com/doc/api/courses.html#method.courses.index

func (*Canvas) CoursesChan

func (c *Canvas) CoursesChan(opts ...Option) <-chan *Course

CoursesChan returns a channel of courses

func (*Canvas) CreateBookmark

func (c *Canvas) CreateBookmark(b *Bookmark) error

CreateBookmark will take a bookmark and send it to canvas.

func (*Canvas) CreateCalendarEvent

func (c *Canvas) CreateCalendarEvent(event *CalendarEvent) (*CalendarEvent, error)

CreateCalendarEvent will send a calendar event to canvas to be created. https://canvas.instructure.com/doc/api/all_resources.html#method.calendar_events_api.create

func (*Canvas) CreateFolder

func (c *Canvas) CreateFolder(path string, opts ...Option) (*Folder, error)

CreateFolder will create a new folder.

func (*Canvas) CurrentAccount

func (c *Canvas) CurrentAccount() (a *Account, err error)

CurrentAccount will get the current account.

func (*Canvas) CurrentUser

func (c *Canvas) CurrentUser(opts ...Option) (*User, error)

CurrentUser get the currently logged in user.

func (*Canvas) DeleteBookmark

func (c *Canvas) DeleteBookmark(b *Bookmark) error

DeleteBookmark will delete a bookmark

func (*Canvas) DeleteCalendarEvent

func (c *Canvas) DeleteCalendarEvent(e *CalendarEvent) (*CalendarEvent, error)

DeleteCalendarEvent will delete the calendar event and return the calendar event deleted.

func (*Canvas) DeleteCalendarEventByID

func (c *Canvas) DeleteCalendarEventByID(id int, opts ...Option) (*CalendarEvent, error)

DeleteCalendarEventByID will delete a calendar event given its ID. This operation returns the calendar event that was deleted.

func (*Canvas) Files

func (c *Canvas) Files(opts ...Option) <-chan *File

Files will return a channel of all the default user's files. https://canvas.instructure.com/doc/api/files.html#method.files.api_index

func (*Canvas) FolderPath

func (c *Canvas) FolderPath(folderpath string) ([]*Folder, error)

FolderPath will get a list of folders in the path given.

func (*Canvas) Folders

func (c *Canvas) Folders(opts ...Option) <-chan *Folder

Folders returns a channel of folders for the current user.

func (*Canvas) GetCourse

func (c *Canvas) GetCourse(id int, opts ...Option) (*Course, error)

GetCourse will get a course given a course id.

https://canvas.instructure.com/doc/api/courses.html#method.courses.show

func (*Canvas) GetFile

func (c *Canvas) GetFile(id int, opts ...Option) (*File, error)

GetFile will get a file by the id.

func (*Canvas) GetUser

func (c *Canvas) GetUser(id int, opts ...Option) (*User, error)

GetUser will return a user object given that user's ID.

func (*Canvas) ListFiles

func (c *Canvas) ListFiles(opts ...Option) ([]*File, error)

ListFiles will return a slice of the current user's files.

func (*Canvas) ListFolders

func (c *Canvas) ListFolders(opts ...Option) ([]*Folder, error)

ListFolders will return a slice of the current user's folders

func (*Canvas) NewFile

func (c *Canvas) NewFile(filename string) *File

NewFile will make a new file object. This will not send any data to canvas.

func (*Canvas) NewFolder

func (c *Canvas) NewFolder(foldername string) *Folder

NewFolder will make a new folder object. This will not send any data to canvas.

func (*Canvas) Root

func (c *Canvas) Root(opts ...Option) (*Folder, error)

Root will get the current user's root folder

func (*Canvas) SearchAccounts

func (c *Canvas) SearchAccounts(term string, opts ...Option) ([]Account, error)

SearchAccounts will search for canvas accounts. Options: name, domain, latitude, longitude

func (*Canvas) SetHost

func (c *Canvas) SetHost(host string) error

SetHost will set the host for the canvas requestor.

func (*Canvas) Todos

func (c *Canvas) Todos() ([]TODO, error)

Todos will get the current user's todo's.

func (*Canvas) UpdateCalendarEvent

func (c *Canvas) UpdateCalendarEvent(event *CalendarEvent) error

UpdateCalendarEvent will update a calendar event. This operation will change event given as an argument. https://canvas.instructure.com/doc/api/all_resources.html#method.calendar_events_api.update

func (*Canvas) UploadFile

func (c *Canvas) UploadFile(filename string, r io.Reader, opts ...Option) (*File, error)

UploadFile uploads a file to the current user's files.

type Conversation

type Conversation struct {
	ID               int         `json:"id"`
	Subject          string      `json:"subject"`
	WorkflowState    string      `json:"workflow_state"`
	LastMessage      string      `json:"last_message"`
	StartAt          time.Time   `json:"start_at"`
	MessageCount     int         `json:"message_count"`
	Subscribed       bool        `json:"subscribed"`
	Private          bool        `json:"private"`
	Starred          bool        `json:"starred"`
	Properties       interface{} `json:"properties"`
	Audience         interface{} `json:"audience"`
	AudienceContexts interface{} `json:"audience_contexts"`
	AvatarURL        string      `json:"avatar_url"`
	Participants     interface{} `json:"participants"`
	Visible          bool        `json:"visible"`
	ContextName      string      `json:"context_name"`
}

Conversation is a conversation.

func Conversations

func Conversations(opts ...Option) ([]Conversation, error)

Conversations returns a list of conversations

type Course

type Course struct {
	ID                   int           `json:"id"`
	Name                 string        `json:"name"`
	SisCourseID          int           `json:"sis_course_id"`
	UUID                 string        `json:"uuid"`
	IntegrationID        string        `json:"integration_id"`
	SisImportID          int           `json:"sis_import_id"`
	CourseCode           string        `json:"course_code"`
	WorkflowState        string        `json:"workflow_state"`
	AccountID            int           `json:"account_id"`
	RootAccountID        int           `json:"root_account_id"`
	EnrollmentTermID     int           `json:"enrollment_term_id"`
	GradingStandardID    int           `json:"grading_standard_id"`
	GradePassbackSetting string        `json:"grade_passback_setting"`
	CreatedAt            time.Time     `json:"created_at"`
	StartAt              time.Time     `json:"start_at"`
	EndAt                time.Time     `json:"end_at"`
	Locale               string        `json:"locale"`
	Enrollments          []*Enrollment `json:"enrollments"`
	TotalStudents        int           `json:"total_students"`
	Calendar             struct {
		// ICS Download is the download link for the calendar
		ICSDownload string `json:"ics"`
	} `json:"calendar"`
	DefaultView       string `json:"default_view"`
	SyllabusBody      string `json:"syllabus_body"`
	NeedsGradingCount int    `json:"needs_grading_count"`

	Term           Term           `json:"term"`
	CourseProgress CourseProgress `json:"course_progress"`

	ApplyAssignmentGroupWeights bool `json:"apply_assignment_group_weights"`
	UserPermissions             struct {
		CreateDiscussionTopic bool `json:"create_discussion_topic"`
		CreateAnnouncement    bool `json:"create_announcement"`
	} `json:"permissions"`
	IsPublic                         bool   `json:"is_public"`
	IsPublicToAuthUsers              bool   `json:"is_public_to_auth_users"`
	PublicSyllabus                   bool   `json:"public_syllabus"`
	PublicSyllabusToAuth             bool   `json:"public_syllabus_to_auth"`
	PublicDescription                string `json:"public_description"`
	StorageQuotaMb                   int    `json:"storage_quota_mb"`
	StorageQuotaUsedMb               int    `json:"storage_quota_used_mb"`
	HideFinalGrades                  bool   `json:"hide_final_grades"`
	License                          string `json:"license"`
	AllowStudentAssignmentEdits      bool   `json:"allow_student_assignment_edits"`
	AllowWikiComments                bool   `json:"allow_wiki_comments"`
	AllowStudentForumAttachments     bool   `json:"allow_student_forum_attachments"`
	OpenEnrollment                   bool   `json:"open_enrollment"`
	SelfEnrollment                   bool   `json:"self_enrollment"`
	RestrictEnrollmentsToCourseDates bool   `json:"restrict_enrollments_to_course_dates"`
	CourseFormat                     string `json:"course_format"`
	AccessRestrictedByDate           bool   `json:"access_restricted_by_date"`
	TimeZone                         string `json:"time_zone"`
	Blueprint                        bool   `json:"blueprint"`
	BlueprintRestrictions            struct {
		Content           bool `json:"content"`
		Points            bool `json:"points"`
		DueDates          bool `json:"due_dates"`
		AvailabilityDates bool `json:"availability_dates"`
	} `json:"blueprint_restrictions"`
	BlueprintRestrictionsByObjectType struct {
		Assignment struct {
			Content bool `json:"content"`
			Points  bool `json:"points"`
		} `json:"assignment"`
		WikiPage struct {
			Content bool `json:"content"`
		} `json:"wiki_page"`
	} `json:"blueprint_restrictions_by_object_type"`
	// contains filtered or unexported fields
}

Course represents a canvas course.

https://canvas.instructure.com/doc/api/courses.html

func Courses

func Courses(opts ...Option) ([]*Course, error)

Courses lists all of the courses associated with that canvas object.

https://canvas.instructure.com/doc/api/courses.html#method.courses.index

func GetCourse

func GetCourse(id int, opts ...Option) (*Course, error)

GetCourse will get a course given a course id.

https://canvas.instructure.com/doc/api/courses.html#method.courses.show

func (*Course) Activity

func (c *Course) Activity() (res interface{}, err error)

Activity returns a course's activity data

func (*Course) Assignment

func (c *Course) Assignment(id int, opts ...Option) (ass *Assignment, err error)

Assignment will get an assignment from the course given an id.

https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.index

func (*Course) Assignments

func (c *Course) Assignments(opts ...Option) <-chan *Assignment

Assignments send the courses assignments over a channel concurrently.

https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.index

func (*Course) ContextCode

func (c *Course) ContextCode() string

ContextCode will return the context code for this specific course.

func (*Course) CreateAssignment

func (c *Course) CreateAssignment(a Assignment, opts ...Option) (*Assignment, error)

CreateAssignment will create an assignment.

func (*Course) CreateFolder

func (c *Course) CreateFolder(path string, opts ...Option) (*Folder, error)

CreateFolder will create a new folder https://canvas.instructure.com/doc/api/files.html#method.folders.create

func (*Course) DeleteAssignment

func (c *Course) DeleteAssignment(a *Assignment) (*Assignment, error)

DeleteAssignment will delete an assignment

func (*Course) DeleteAssignmentByID

func (c *Course) DeleteAssignmentByID(id int) (*Assignment, error)

DeleteAssignmentByID will delete an assignment givent only an assignment ID.

func (*Course) DiscussionTopics

func (c *Course) DiscussionTopics(opts ...Option) ([]*DiscussionTopic, error)

DiscussionTopics return a list of the course discussion topics.

func (*Course) EditAssignment

func (c *Course) EditAssignment(a *Assignment) (*Assignment, error)

EditAssignment will edit the assignment given. Returns the new edited assignment.

func (*Course) File

func (c *Course) File(id int, opts ...Option) (*File, error)

File will get a specific file id.

func (*Course) Files

func (c *Course) Files(opts ...Option) <-chan *File

Files returns a channel of all the course's files

func (*Course) Folder

func (c *Course) Folder(id int, opts ...Option) (*Folder, error)

Folder will the a folder from the course given a folder id. https://canvas.instructure.com/doc/api/files.html#method.folders.show

func (*Course) FolderPath

func (c *Course) FolderPath(pth string) ([]*Folder, error)

FolderPath will split the path and return a list containing all of the folders in the path.

func (*Course) Folders

func (c *Course) Folders(opts ...Option) <-chan *Folder

Folders will retrieve the course's folders. https://canvas.instructure.com/doc/api/files.html#method.folders.list_all_folders

func (*Course) ListAssignments

func (c *Course) ListAssignments(opts ...Option) (asses []*Assignment, err error)

ListAssignments will get all the course assignments and put them in a slice.

func (*Course) ListFiles

func (c *Course) ListFiles(opts ...Option) ([]*File, error)

ListFiles returns a slice of files for the course.

func (*Course) ListFolders

func (c *Course) ListFolders(opts ...Option) ([]*Folder, error)

ListFolders returns a slice of folders for the course. https://canvas.instructure.com/doc/api/files.html#method.folders.list_all_folders

func (*Course) Permissions

func (c *Course) Permissions() (*Permissions, error)

Permissions get the current user's permissions with respect to the course object.

func (*Course) Quiz

func (c *Course) Quiz(id int, opts ...Option) (*Quiz, error)

Quiz will return a quiz given a quiz id.

func (*Course) Quizzes

func (c *Course) Quizzes(opts ...Option) ([]*Quiz, error)

Quizzes will get all the course quizzes

func (*Course) Root

func (c *Course) Root(opts ...Option) (*Folder, error)

Root will get the root folder for the course.

func (*Course) SearchUsers

func (c *Course) SearchUsers(term string, opts ...Option) (users []*User, err error)

SearchUsers will search for a user in the course

func (*Course) SetErrorHandler

func (c *Course) SetErrorHandler(f errorHandlerFunc)

SetErrorHandler will set a error handling callback that is used to handle errors in goroutines. The default error handler will simply panic.

The callback should accept an error and a quit channel. If a value is sent on the quit channel, whatever secsion of code is receiving the channel will end gracefully.

func (*Course) Settings

func (c *Course) Settings(opts ...Option) (cs *CourseSettings, err error)

Settings gets the course settings

func (*Course) UpdateSettings

func (c *Course) UpdateSettings(settings *CourseSettings) (*CourseSettings, error)

UpdateSettings will update a user's settings based on a given settings struct and will return the updated settings struct.

func (*Course) UploadFile

func (c *Course) UploadFile(filename string, r io.Reader, opts ...Option) (*File, error)

UploadFile will upload a file to the course. https://canvas.instructure.com/doc/api/courses.html#method.courses.create_file

func (*Course) User

func (c *Course) User(id int, opts ...Option) (*User, error)

User gets a specific user.

func (*Course) Users

func (c *Course) Users(opts ...Option) (users []*User, err error)

Users will get a list of users in the course

type CourseProgress

type CourseProgress struct {
	RequirementCount          int       `json:"requirement_count"`
	RequirementCompletedCount int       `json:"requirement_completed_count"`
	NextRequirementURL        string    `json:"next_requirement_url"`
	CompletedAt               time.Time `json:"completed_at"`
}

CourseProgress is the progress through a course.

type CourseSettings

type CourseSettings struct {
	AllowStudentDiscussionTopics  bool `json:"allow_student_discussion_topics"`
	AllowStudentForumAttachments  bool `json:"allow_student_forum_attachments"`
	AllowStudentDiscussionEditing bool `json:"allow_student_discussion_editing"`
	GradingStandardEnabled        bool `json:"grading_standard_enabled"`
	GradingStandardID             int  `json:"grading_standard_id"`
	AllowStudentOrganizedGroups   bool `json:"allow_student_organized_groups"`
	HideFinalGrades               bool `json:"hide_final_grades"`
	HideDistributionGraphs        bool `json:"hide_distribution_graphs"`
	LockAllAnnouncements          bool `json:"lock_all_announcements"`
	UsageRightsRequired           bool `json:"usage_rights_required"`
}

CourseSettings is a json struct for a course's settings.

type DiscussionTopic

type DiscussionTopic struct {
	ID                      int         `json:"id"`
	Title                   string      `json:"title"`
	Message                 string      `json:"message"`
	HTMLURL                 string      `json:"html_url"`
	PostedAt                time.Time   `json:"posted_at"`
	LastReplyAt             time.Time   `json:"last_reply_at"`
	RequireInitialPost      bool        `json:"require_initial_post"`
	UserCanSeePosts         bool        `json:"user_can_see_posts"`
	DiscussionSubentryCount int         `json:"discussion_subentry_count"`
	ReadState               string      `json:"read_state"`
	UnreadCount             int         `json:"unread_count"`
	Subscribed              bool        `json:"subscribed"`
	SubscriptionHold        string      `json:"subscription_hold"`
	AssignmentID            interface{} `json:"assignment_id"`
	DelayedPostAt           interface{} `json:"delayed_post_at"`
	Published               bool        `json:"published"`
	LockAt                  interface{} `json:"lock_at"`
	Locked                  bool        `json:"locked"`
	Pinned                  bool        `json:"pinned"`
	LockedForUser           bool        `json:"locked_for_user"`
	LockInfo                interface{} `json:"lock_info"`
	LockExplanation         string      `json:"lock_explanation"`
	UserName                string      `json:"user_name"`
	TopicChildren           []int       `json:"topic_children"`
	GroupTopicChildren      []struct {
		ID      int `json:"id"`
		GroupID int `json:"group_id"`
	} `json:"group_topic_children"`
	RootTopicID     interface{} `json:"root_topic_id"`
	PodcastURL      string      `json:"podcast_url"`
	DiscussionType  string      `json:"discussion_type"`
	GroupCategoryID interface{} `json:"group_category_id"`
	Attachments     interface{} `json:"attachments"`
	Permissions     struct {
		Attach bool `json:"attach"`
	} `json:"permissions"`
	AllowRating        bool `json:"allow_rating"`
	OnlyGradersCanRate bool `json:"only_graders_can_rate"`
	SortByRating       bool `json:"sort_by_rating"`
}

DiscussionTopic is a discussion topic

func Announcements

func Announcements(
	contextCodes []string,
	opts ...Option,
) ([]*DiscussionTopic, error)

Announcements will get the announcements

type Enrollment

type Enrollment struct {
	ID                   int    `json:"id"`
	CourseID             int    `json:"course_id"`
	CourseIntegrationID  string `json:"course_integration_id"`
	CourseSectionID      int    `json:"course_section_id"`
	SectionIntegrationID string `json:"section_integration_id"`

	EnrollmentState                string `json:"enrollment_state"`
	Role                           string `json:"role"`
	RoleID                         int    `json:"role_id"`
	Type                           string `json:"type"`
	LimitPrivilegesToCourseSection bool   `json:"limit_privileges_to_course_section"`
	UserID                         int    `json:"user_id"`
	User                           *User  `json:"user"`

	SisCourseID      string      `json:"sis_course_id"`
	SisAccountID     string      `json:"sis_account_id"`
	SisSectionID     string      `json:"sis_section_id"`
	SisUserID        string      `json:"sis_user_id"`
	SisImportID      int         `json:"sis_import_id"`
	RootAccountID    int         `json:"root_account_id"`
	AssociatedUserID interface{} `json:"associated_user_id"`

	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
	StartAt           time.Time `json:"start_at"`
	EndAt             time.Time `json:"end_at"`
	LastActivityAt    time.Time `json:"last_activity_at"`
	LastAttendedAt    time.Time `json:"last_attended_at"`
	TotalActivityTime int       `json:"total_activity_time"`

	HTMLURL string `json:"html_url"`
	Grades  struct {
		HTMLURL              string  `json:"html_url"`
		CurrentScore         float64 `json:"current_score"`
		CurrentGrade         string  `json:"current_grade"`
		FinalScore           float64 `json:"final_score"`
		FinalGrade           string  `json:"final_grade"`
		UnpostedCurrentGrade string  `json:"unposted_current_grade"`
		UnpostedFinalGrade   string  `json:"unposted_final_grade"`
		UnpostedCurrentScore string  `json:"unposted_current_score"`
		UnpostedFinalScore   string  `json:"unposted_final_score"`
	} `json:"grades"`
	OverrideGrade                     string  `json:"override_grade"`
	OverrideScore                     float64 `json:"override_score"`
	UnpostedCurrentGrade              string  `json:"unposted_current_grade"`
	UnpostedFinalGrade                string  `json:"unposted_final_grade"`
	UnpostedCurrentScore              string  `json:"unposted_current_score"`
	UnpostedFinalScore                string  `json:"unposted_final_score"`
	HasGradingPeriods                 bool    `json:"has_grading_periods"`
	TotalsForAllGradingPeriodsOption  bool    `json:"totals_for_all_grading_periods_option"`
	CurrentGradingPeriodTitle         string  `json:"current_grading_period_title"`
	CurrentGradingPeriodID            int     `json:"current_grading_period_id"`
	CurrentPeriodOverrideGrade        string  `json:"current_period_override_grade"`
	CurrentPeriodOverrideScore        float64 `json:"current_period_override_score"`
	CurrentPeriodUnpostedCurrentScore float64 `json:"current_period_unposted_current_score"`
	CurrentPeriodUnpostedFinalScore   float64 `json:"current_period_unposted_final_score"`
	CurrentPeriodUnpostedCurrentGrade string  `json:"current_period_unposted_current_grade"`
	CurrentPeriodUnpostedFinalGrade   string  `json:"current_period_unposted_final_grade"`
}

Enrollment is an enrollment object https://canvas.instructure.com/doc/api/enrollments.html

type Error

type Error struct {
	Errors struct {
		EndDate string `json:"end_date"`
	} `json:"errors"`
	Message string `json:"message"`

	Err      string `json:"error"`
	SentryID string `json:"sentryId"`

	Status string `json:"-"`
}

Error is an error response.

func (*Error) Error

func (e *Error) Error() string

type File

type File struct {
	ID       int    `json:"id"`
	FolderID int    `json:"folder_id"`
	URL      string `json:"url"`
	UUID     string `json:"uuid"`

	Filename    string    `json:"filename"`
	DisplayName string    `json:"display_name"`
	ContentType string    `json:"content-type"`
	Size        int       `json:"size"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	ModifiedAt  time.Time `json:"modified_at"`

	Locked          bool        `json:"locked"`
	LockAt          time.Time   `json:"lock_at"`
	UnlockAt        time.Time   `json:"unlock_at"`
	LockedForUser   bool        `json:"locked_for_user"`
	LockInfo        interface{} `json:"lock_info"`
	LockExplanation string      `json:"lock_explanation"`

	Hidden        bool   `json:"hidden"`
	HiddenForUser bool   `json:"hidden_for_user"`
	ThumbnailURL  string `json:"thumbnail_url"`
	PreviewURL    string `json:"preview_url"`
	MimeClass     string `json:"mime_class"`
	MediaEntryID  string `json:"media_entry_id"`
	UploadStatus  string `json:"upload_status"`
	// contains filtered or unexported fields
}

File is a file. https://canvas.instructure.com/doc/api/files.html

func GetFile

func GetFile(id int, opts ...Option) (*File, error)

GetFile will get a file by the id.

func ListFiles

func ListFiles(opts ...Option) ([]*File, error)

ListFiles will return a slice of the current user's files.

func NewFile

func NewFile(filename string) *File

NewFile will make a new file object. This will not send any data to canvas.

func UploadFile

func UploadFile(filename string, r io.Reader, opts ...Option) (*File, error)

UploadFile uploads a file to the current user's files.

func (*File) AsReadCloser

func (f *File) AsReadCloser() (io.ReadCloser, error)

AsReadCloser will return the contents of the file in an io.ReadCloser.

This function will make an http request to get the data

func (*File) AsWriteCloser

func (f *File) AsWriteCloser() (io.WriteCloser, error)

AsWriteCloser returns an io.WriteCloser that uploads any data that has been written to it. All data written will be sent to the file when the Close function is called. Calling Close will also update the file that is creating the WriteCloser.

This function may make an http request to find the parent folder.

Example
file := canvas.NewFile("test-file")
fmt.Println(file.ID == 0)

wc, err := file.AsWriteCloser()
if err != nil {
	log.Fatal("could not create io.WriteCloser:", err)
}
if _, err = io.WriteString(wc, "this is a test file for the examples"); err != nil {
	log.Fatal("could not write data:", err)
}
// close sends the data to canvas and updates the 'file' pointer
if err = wc.Close(); err != nil {
	log.Fatal("could not send data: ", err)
}
fmt.Println(file.ID == 0)
Output:

true
false

func (*File) Copy

func (f *File) Copy(dest *Folder) error

Copy the file into another folder. https://canvas.instructure.com/doc/api/files.html#method.folders.copy_file

func (*File) Delete

func (f *File) Delete(opts ...Option) error

Delete the file. https://canvas.instructure.com/doc/api/files.html#method.files.destroy

func (*File) GetID

func (f *File) GetID() int

GetID is for the FileType interface

func (*File) Hide

func (f *File) Hide() error

Hide the file

func (*File) Move

func (f *File) Move(dest *Folder) error

Move a file to another folder. https://canvas.instructure.com/doc/api/files.html#method.files.api_update

func (*File) Name

func (f *File) Name() string

Name returns the file's filename

func (*File) ParentFolder

func (f *File) ParentFolder() (*Folder, error)

ParentFolder will get the folder that the file is a part of.

func (*File) Path

func (f *File) Path() string

Path returns the folder path that the file is in.

func (*File) PublicURL

func (f *File) PublicURL() (string, error)

PublicURL will get the file's public url.

func (*File) Type

func (f *File) Type() FileObjType

Type returns canvas.TypeFile

func (*File) Unhide

func (f *File) Unhide() error

Unhide the file

func (*File) WriteTo

func (f *File) WriteTo(w io.Writer) (int64, error)

WriteTo will write the contents of the file to an io.Writer

type FileObj

type FileObj interface {
	GetID() int
	Type() FileObjType
	Name() string
	Path() string

	Move(*Folder) error
	Rename(string) error
	Copy(*Folder) error
	Delete(...Option) error
	Hide() error
	Unhide() error

	ParentFolder() (*Folder, error)
}

FileObj is a interface for filesystem objects

type FileObjType

type FileObjType int

FileObjType is the type of a file

const (
	// TypeFile is the type for files
	TypeFile FileObjType = iota
	// TypeFolder is the type for folders
	TypeFolder
)

type Folder

type Folder struct {
	ID             int    `json:"id"`
	ParentFolderID int    `json:"parent_folder_id"`
	Foldername     string `json:"name"`
	FullName       string `json:"full_name"`

	FilesURL   string `json:"files_url"`
	FoldersURL string `json:"folders_url"`

	ContextType string `json:"context_type"`
	// if ContextType is "Course" ContextID will be the course id, if
	// its "User" then it will be the user id and so on.
	ContextID int `json:"context_id"`

	Position     int `json:"position"`
	FilesCount   int `json:"files_count"`
	FoldersCount int `json:"folders_count"`

	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
	LockAt         time.Time `json:"lock_at"`
	UnlockAt       time.Time `json:"unlock_at"`
	Locked         bool      `json:"locked"`
	Hidden         bool      `json:"hidden"`
	HiddenForUser  bool      `json:"hidden_for_user"`
	LockedForUser  bool      `json:"locked_for_user"`
	ForSubmissions bool      `json:"for_submissions"`
	// contains filtered or unexported fields
}

Folder is a folder https://canvas.instructure.com/doc/api/files.html

func CreateFolder

func CreateFolder(path string, opts ...Option) (*Folder, error)

CreateFolder will create a new folder.

func FolderPath

func FolderPath(path string) ([]*Folder, error)

FolderPath will get a list of folders in the path given.

func ListFolders

func ListFolders(opts ...Option) ([]*Folder, error)

ListFolders will return a slice of the current user's folders

func NewFolder

func NewFolder(foldername string) *Folder

NewFolder will make a new folder object. This will not send any data to canvas.

func Root

func Root(opts ...Option) (*Folder, error)

Root will get the current user's root folder

func (*Folder) Copy

func (f *Folder) Copy(dest *Folder) error

Copy the folder to a another folder (dest) https://canvas.instructure.com/doc/api/files.html#method.folders.copy_folder

func (*Folder) CreateFolder

func (f *Folder) CreateFolder(path string, opts ...Option) (*Folder, error)

CreateFolder creates a new folder as a subfolder of the current one. https://canvas.instructure.com/doc/api/files.html#method.folders.create

func (*Folder) File

func (f *Folder) File(id int, opts ...Option) (*File, error)

File gets a file by id. https://canvas.instructure.com/doc/api/files.html#method.files.api_show

func (*Folder) Files

func (f *Folder) Files(opts ...Option) <-chan *File

Files will return a channel that sends all of the files in the folder. https://canvas.instructure.com/doc/api/files.html#method.files.api_index

func (*Folder) Folders

func (f *Folder) Folders(opts ...Option) <-chan *Folder

Folders will return a channel that sends all of the sub-folders. https://canvas.instructure.com/doc/api/files.html#method.folders.api_index

func (*Folder) GetID

func (f *Folder) GetID() int

GetID will return the folder id, this is only here for interfaces.

func (*Folder) Hide

func (f *Folder) Hide() error

Hide the folder

func (*Folder) ListFiles

func (f *Folder) ListFiles(opts ...Option) ([]*File, error)

ListFiles will list all of the files that are in the folder.

func (*Folder) ListFolders

func (f *Folder) ListFolders(opts ...Option) ([]*Folder, error)

ListFolders will collect all the folders in a slice of Folders. https://canvas.instructure.com/doc/api/files.html#method.folders.api_index

func (*Folder) Move

func (f *Folder) Move(dest *Folder) error

Move the folder into another folder

func (*Folder) Name

func (f *Folder) Name() string

Name returns only the folder's name without the path.

func (*Folder) ParentFolder

func (f *Folder) ParentFolder() (*Folder, error)

ParentFolder will get the folder's parent folder.

func (*Folder) Path

func (f *Folder) Path() string

Path wil return only the folder's path without it's name.

func (*Folder) Rename

func (f *Folder) Rename(name string) error

Rename the folder.

func (*Folder) Type

func (f *Folder) Type() FileObjType

Type returns canvas.TypeFolder

func (*Folder) Unhide

func (f *Folder) Unhide() error

Unhide the folder

func (*Folder) UploadFile

func (f *Folder) UploadFile(
	filename string,
	r io.Reader,
	opts ...Option,
) (*File, error)

UploadFile uploads a file into a specific file.

type GradingType

type GradingType string

GradingType is a grading type

const (
	// PassFail is the grading type for pass fail assignments
	PassFail GradingType = "pass_fail"
	// Percent is the grading type for percent graded assignments
	Percent GradingType = "percent"
	// LetterGrade is the grading type for letter grade assignments
	LetterGrade GradingType = "letter_grade"
	// GPAScale is the grading type for GPA scale assignments
	GPAScale GradingType = "gpa_scale"
	// Points is the grading type for point graded assignments
	Points GradingType = "points"
	// NotGraded is the grading type for assignments that are not graded
	NotGraded GradingType = "not_graded"
)

type LockInfo

type LockInfo struct {
	AssetString    string    `json:"asset_string"`
	UnlockAt       time.Time `json:"unlock_at"`
	LockAt         time.Time `json:"lock_at"`
	ContextModule  string    `json:"context_module"`
	ManuallyLocked bool      `json:"manually_locked"`
}

LockInfo is a struct containing assignment lock status.

type Option

type Option interface {
	Name() string
	Value() []string
}

Option is a key value pair used for api parameters. see Opt

var (
	CompletedCourses        Option = Opt("enrollment_state", "completed")
	ActiveCourses           Option = Opt("enrollment_state", "active")
	InvitedOrPendingCourses Option = Opt("enrollment_state", "invited_or_pending")
)

Course options are given when requesting courses in order to filter out certain courses that may not be wanted in the query.

var (
	OptTeacher  Option = Opt("enrollment_type", "teacher")
	OptStudent  Option = Opt("enrollment_type", "student")
	OptTA       Option = Opt("enrollment_type", "ta")
	OptObserver Option = Opt("enrollment_type", "observer")
	OptDesigner Option = Opt("enrollment_type", "designer")
)

Enrollment options are given to filter out different types of people

func ArrayOpt

func ArrayOpt(key string, vals ...string) Option

ArrayOpt creates an option that will be sent as an array of options (ex. include[], content_type[], etc.)

func ContentType

func ContentType(contentType string) Option

ContentType retruns a option param for getting a content type. Generally used for file uploads.

func ContentTypes

func ContentTypes(contentTypes ...string) Option

ContentTypes retruns a option param for getting a content type. As a rule of thumb this is used for searches or filtering.

func DateOpt

func DateOpt(key string, date time.Time) Option

DateOpt will return an Option with a correctly formatted date.

func IncludeOpt

func IncludeOpt(vals ...string) Option

IncludeOpt is the option for any "include[]" api parameters.

func Opt

func Opt(key string, val interface{}) Option

Opt creates a new option. Used for creating a new Param interface.

func SortOpt

func SortOpt(schemes ...string) Option

SortOpt returns a sorting option

func UserOpt

func UserOpt(key, val string) Option

UserOpt creates an Option that should be sent when asking for a user, updating a user, or creating a user.

type Permissions

type Permissions struct {
	Read                        bool `json:"read"`
	ReadOutcomes                bool `json:"read_outcomes"`
	ReadSyllabus                bool `json:"read_syllabus"`
	ManageCanvasnetCourses      bool `json:"manage_canvasnet_courses"`
	ProvisionCatalog            bool `json:"provision_catalog"`
	CreateAccounts              bool `json:"create_accounts"`
	ManageLinks                 bool `json:"manage_links"`
	SuspendAccounts             bool `json:"suspend_accounts"`
	ManageDemos                 bool `json:"manage_demos"`
	BecomeUser                  bool `json:"become_user"`
	ImportSis                   bool `json:"import_sis"`
	ManageAccountMemberships    bool `json:"manage_account_memberships"`
	ManageAccountSettings       bool `json:"manage_account_settings"`
	ManageAlerts                bool `json:"manage_alerts"`
	ManageCatalog               bool `json:"manage_catalog"`
	ManageCourses               bool `json:"manage_courses"`
	ManageDataServices          bool `json:"manage_data_services"`
	ManageCourseVisibility      bool `json:"manage_course_visibility"`
	ManageDeveloperKeys         bool `json:"manage_developer_keys"`
	ModerateUserContent         bool `json:"moderate_user_content"`
	ManageFeatureFlags          bool `json:"manage_feature_flags"`
	ManageFrozenAssignments     bool `json:"manage_frozen_assignments"`
	ManageGlobalOutcomes        bool `json:"manage_global_outcomes"`
	ManageJobs                  bool `json:"manage_jobs"`
	ManageMasterCourses         bool `json:"manage_master_courses"`
	ManageRoleOverrides         bool `json:"manage_role_overrides"`
	ManageStorageQuotas         bool `json:"manage_storage_quotas"`
	ManageSis                   bool `json:"manage_sis"`
	ManageSiteSettings          bool `json:"manage_site_settings"`
	ManageUserLogins            bool `json:"manage_user_logins"`
	ManageUserObservers         bool `json:"manage_user_observers"`
	ReadCourseContent           bool `json:"read_course_content"`
	ReadCourseList              bool `json:"read_course_list"`
	ReadMessages                bool `json:"read_messages"`
	ResetAnyMfa                 bool `json:"reset_any_mfa"`
	UndeleteCourses             bool `json:"undelete_courses"`
	ChangeCourseState           bool `json:"change_course_state"`
	CreateCollaborations        bool `json:"create_collaborations"`
	CreateConferences           bool `json:"create_conferences"`
	CreateForum                 bool `json:"create_forum"`
	GenerateObserverPairingCode bool `json:"generate_observer_pairing_code"`
	ImportOutcomes              bool `json:"import_outcomes"`
	LtiAddEdit                  bool `json:"lti_add_edit"`
	ManageAdminUsers            bool `json:"manage_admin_users"`
	ManageAssignments           bool `json:"manage_assignments"`
	ManageCalendar              bool `json:"manage_calendar"`
	ManageContent               bool `json:"manage_content"`
	ManageFiles                 bool `json:"manage_files"`
	ManageGrades                bool `json:"manage_grades"`
	ManageGroups                bool `json:"manage_groups"`
	ManageInteractionAlerts     bool `json:"manage_interaction_alerts"`
	ManageOutcomes              bool `json:"manage_outcomes"`
	ManageSections              bool `json:"manage_sections"`
	ManageStudents              bool `json:"manage_students"`
	ManageUserNotes             bool `json:"manage_user_notes"`
	ManageRubrics               bool `json:"manage_rubrics"`
	ManageWiki                  bool `json:"manage_wiki"`
	ManageWikiCreate            bool `json:"manage_wiki_create"`
	ManageWikiDelete            bool `json:"manage_wiki_delete"`
	ManageWikiUpdate            bool `json:"manage_wiki_update"`
	ModerateForum               bool `json:"moderate_forum"`
	PostToForum                 bool `json:"post_to_forum"`
	ReadAnnouncements           bool `json:"read_announcements"`
	ReadEmailAddresses          bool `json:"read_email_addresses"`
	ReadForum                   bool `json:"read_forum"`
	ReadQuestionBanks           bool `json:"read_question_banks"`
	ReadReports                 bool `json:"read_reports"`
	ReadRoster                  bool `json:"read_roster"`
	ReadSis                     bool `json:"read_sis"`
	SelectFinalGrade            bool `json:"select_final_grade"`
	SendMessages                bool `json:"send_messages"`
	SendMessagesAll             bool `json:"send_messages_all"`

	ViewAnalytics         bool `json:"view_analytics"`
	ViewAuditTrail        bool `json:"view_audit_trail"`
	ViewAllGrades         bool `json:"view_all_grades"`
	ViewGroupPages        bool `json:"view_group_pages"`
	ViewQuizAnswerAudits  bool `json:"view_quiz_answer_audits"`
	ViewFeatureFlags      bool `json:"view_feature_flags"`
	ViewUserLogins        bool `json:"view_user_logins"`
	ViewLearningAnalytics bool `json:"view_learning_analytics"`
	ViewUnpublishedItems  bool `json:"view_unpublished_items"`
	ViewCourseChanges     bool `json:"view_course_changes"`
	ViewErrorReports      bool `json:"view_error_reports"`
	ViewGradeChanges      bool `json:"view_grade_changes"`
	ViewJobs              bool `json:"view_jobs"`
	ViewNotifications     bool `json:"view_notifications"`
	ViewStatistics        bool `json:"view_statistics"`

	ParticipateAsStudent bool `json:"participate_as_student"`
	ReadGrades           bool `json:"read_grades"`
	Update               bool `json:"update"`
	Delete               bool `json:"delete"`
	ReadAsAdmin          bool `json:"read_as_admin"`
	Manage               bool `json:"manage"`
	UseStudentView       bool `json:"use_student_view"`
	ReadRubrics          bool `json:"read_rubrics"`
	ResetContent         bool `json:"reset_content"`
	ReadPriorRoster      bool `json:"read_prior_roster"`
	CreateToolManually   bool `json:"create_tool_manually"`
}

Permissions is a canvas user permissions object

type Quiz

type Quiz struct {
	ID       int       `json:"id"`
	Title    string    `json:"title"`
	DueAt    time.Time `json:"due_at"`
	LockAt   time.Time `json:"lock_at"`
	UnlockAt time.Time `json:"unlock_at"`

	HTMLURL                       string          `json:"html_url"`
	MobileURL                     string          `json:"mobile_url"`
	PreviewURL                    string          `json:"preview_url"`
	Description                   string          `json:"description"`
	QuizType                      string          `json:"quiz_type"`
	AssignmentGroupID             int             `json:"assignment_group_id"`
	TimeLimit                     int             `json:"time_limit"`
	ShuffleAnswers                bool            `json:"shuffle_answers"`
	HideResults                   string          `json:"hide_results"`
	ShowCorrectAnswers            bool            `json:"show_correct_answers"`
	ShowCorrectAnswersLastAttempt bool            `json:"show_correct_answers_last_attempt"`
	ShowCorrectAnswersAt          time.Time       `json:"show_correct_answers_at"`
	HideCorrectAnswersAt          time.Time       `json:"hide_correct_answers_at"`
	OneTimeResults                bool            `json:"one_time_results"`
	ScoringPolicy                 string          `json:"scoring_policy"`
	AllowedAttempts               int             `json:"allowed_attempts"`
	OneQuestionAtATime            bool            `json:"one_question_at_a_time"`
	QuestionCount                 int             `json:"question_count"`
	PointsPossible                int             `json:"points_possible"`
	CantGoBack                    bool            `json:"cant_go_back"`
	AccessCode                    string          `json:"access_code"`
	IPFilter                      string          `json:"ip_filter"`
	Published                     bool            `json:"published"`
	Unpublishable                 bool            `json:"unpublishable"`
	LockedForUser                 bool            `json:"locked_for_user"`
	LockInfo                      interface{}     `json:"lock_info"`
	LockExplanation               string          `json:"lock_explanation"`
	SpeedgraderURL                string          `json:"speedgrader_url"`
	QuizExtensionsURL             string          `json:"quiz_extensions_url"`
	Permissions                   QuizPermissions `json:"permissions"`
	AllDates                      []string        `json:"all_dates"`
	VersionNumber                 int             `json:"version_number"`
	QuestionTypes                 []string        `json:"question_types"`
	AnonymousSubmissions          bool            `json:"anonymous_submissions"`
}

Quiz is a quiz json response.

type QuizPermissions

type QuizPermissions struct {
	Read           bool `json:"read"`
	Submit         bool `json:"submit"`
	Create         bool `json:"create"`
	Manage         bool `json:"manage"`
	ReadStatistics bool `json:"read_statistics"`
	ReviewGrades   bool `json:"review_grades"`
	Update         bool `json:"update"`
}

QuizPermissions is the permissions for a quiz.

type RubricCriteria

type RubricCriteria struct {
	Points            float64 `json:"points"`
	ID                string  `json:"id"`
	LearningOutcomeID string  `json:"learning_outcome_id"`
	VendorGUID        string  `json:"vendor_guid"`
	Description       string  `json:"description"`
	LongDescription   string  `json:"long_description"`
	CriterionUseRange bool    `json:"criterion_use_range"`
	Ratings           []struct {
		ID              string  `json:"id"`
		Description     string  `json:"description"`
		LongDescription string  `json:"long_description"`
		Points          float64 `json:"points"`
	} `json:"ratings"`
	IgnoreForScoring bool `json:"ignore_for_scoring"`
}

RubricCriteria has the rubric information for an assignment.

type Submission

type Submission struct {
	// A submission type can be any of:
	//	- "online_text_entry"
	//	- "online_url"
	//	- "online_upload"
	//	- "media_recording"
	Type                          string      `json:"submission_type" url:"submission_type"`
	AssignmentID                  int         `json:"assignment_id"`
	Assignment                    interface{} `json:"assignment"`
	Course                        interface{} `json:"course"`
	Attempt                       int         `json:"attempt"`
	Body                          string      `json:"body,omitempty"`
	Grade                         string      `json:"grade"`
	GradeMatchesCurrentSubmission bool        `json:"grade_matches_current_submission"`
	HTMLURL                       string      `json:"html_url,omitempty"`
	PreviewURL                    string      `json:"preview_url"`
	Score                         float64     `json:"score"`
	Comments                      interface{} `json:"submission_comments"`
	SubmittedAt                   time.Time   `json:"submitted_at"`
	PostedAt                      time.Time   `json:"posted_at"`
	URL                           string      `json:"url,omitempty"`
	GraderID                      int         `json:"grader_id"`
	GradedAt                      time.Time   `json:"graded_at"`
	UserID                        int         `json:"user_id"`
	User                          interface{} `json:"user" url:"-"`
	Late                          bool        `json:"late"`
	AssignmentVisible             bool        `json:"assignment_visible"`
	Excused                       bool        `json:"excused"`
	Missing                       bool        `json:"missing"`
	LatePolicyStatus              string      `json:"late_policy_status"`
	PointsDeducted                float64     `json:"points_deducted"`
	SecondsLate                   int         `json:"seconds_late"`
	WorkflowState                 string      `json:"workflow_state"`
	ExtraAttempts                 int         `json:"extra_attempts"`
	AnonymousID                   string      `json:"anonymous_id"`

	// Used assignment submission
	FileIDs          []int  `json:"-" url:"file_ids,omitempty"`
	MediaCommentID   string `json:"-" url:"media_comment_id,omitempty"`
	MediaCommentType string `json:"-" url:"media_comment_type,omitempty"` // "audio" or "video"
}

Submission is a submission type.

type TODO

type TODO struct {
	Type              string      `json:"type"`
	Assignment        *Assignment `json:"assignment"`
	Quiz              *Quiz       `json:"quiz"`
	Ignore            string      `json:"ignore"`
	IgnorePerminantly string      `json:"ignore_perminantly"`
	HTMLURL           string      `json:"html_url"`
	NeedsGradingCount int         `json:"needs_grading_count"`
	ContextType       string      `json:"context_type"`
	ContextID         int         `json:"context_id"`
	CourseID          int         `json:"course_id"`
	GroupID           interface{} `json:"group_id"`
}

TODO is a to-do struct

func Todos

func Todos() ([]TODO, error)

Todos will get the current user's todo's.

type Term

type Term struct {
	ID      int
	Name    string
	StartAt time.Time `json:"start_at"`
	EndAt   time.Time `json:"end_at"`
}

Term is a school term. One school year.

type TurnitinSettings

type TurnitinSettings struct {
	OriginalityReportVisibility string `json:"originality_report_visibility"`
	SPaperCheck                 bool   `json:"s_paper_check"`
	InternetCheck               bool   `json:"internet_check"`
	JournalCheck                bool   `json:"journal_check"`
	ExcludeBiblio               bool   `json:"exclude_biblio"`
	ExcludeQuoted               bool   `json:"exclude_quoted"`
	ExcludeSmallMatchesType     string `json:"exclude_small_matches_type"`
	ExcludeSmallMatchesValue    int    `json:"exclude_small_matches_value"`
}

TurnitinSettings is a settings struct for turnitin

type User

type User struct {
	ID              int          `json:"id"`
	Name            string       `json:"name"`
	Email           string       `json:"email"`
	Bio             string       `json:"bio"`
	SortableName    string       `json:"sortable_name"`
	ShortName       string       `json:"short_name"`
	SisUserID       string       `json:"sis_user_id"`
	SisImportID     int          `json:"sis_import_id"`
	IntegrationID   string       `json:"integration_id"`
	CreatedAt       time.Time    `json:"created_at"`
	LoginID         string       `json:"login_id"`
	AvatarURL       string       `json:"avatar_url"`
	Enrollments     []Enrollment `json:"enrollments"`
	Locale          string       `json:"locale"`
	EffectiveLocale string       `json:"effective_locale"`
	LastLogin       time.Time    `json:"last_login"`
	TimeZone        string       `json:"time_zone"`

	CanUpdateAvatar bool `json:"can_update_avatar"`
	Permissions     struct {
		CanUpdateName           bool `json:"can_update_name"`
		CanUpdateAvatar         bool `json:"can_update_avatar"`
		LimitParentAppWebAccess bool `json:"limit_parent_app_web_access"`
	} `json:"permissions"`
	// contains filtered or unexported fields
}

User is a canvas user

func CurrentUser

func CurrentUser(opts ...Option) (*User, error)

CurrentUser get the currently logged in user.

func GetUser

func GetUser(id int, opts ...Option) (*User, error)

GetUser will return a user object given that user's ID.

func (*User) Avatars

func (u *User) Avatars() (av []Avatar, err error)

Avatars will get a list of the user's avatars.

func (*User) Bookmarks

func (u *User) Bookmarks(opts ...Option) (bks []Bookmark, err error)

Bookmarks will get the user's bookmarks

func (*User) CalendarEvents

func (u *User) CalendarEvents(opts ...Option) (cal []CalendarEvent, err error)

CalendarEvents gets the user's calendar events.

func (*User) Color

func (u *User) Color(asset string) (color *UserColor, err error)

Color will get a specific color from the user's profile.

func (*User) Colors

func (u *User) Colors() (map[string]string, error)

Colors will return a map of the user's custom profile colors.

func (*User) ContextCode

func (u *User) ContextCode() string

ContextCode returns the context code for the user.

func (*User) Courses

func (u *User) Courses(opts ...Option) ([]*Course, error)

Courses will return the user's courses.

func (*User) CreateBookmark

func (u *User) CreateBookmark(b *Bookmark) error

CreateBookmark will create a bookmark

func (*User) CreateFolder

func (u *User) CreateFolder(path string, opts ...Option) (*Folder, error)

CreateFolder will create a new folder.

func (*User) DeleteBookmark

func (u *User) DeleteBookmark(b *Bookmark) error

DeleteBookmark will delete a user's bookmark.

func (*User) FavoriteCourses

func (u *User) FavoriteCourses(opts ...Option) ([]*Course, error)

FavoriteCourses returns the user's list of favorites courses.

func (*User) File

func (u *User) File(id int, opts ...Option) (*File, error)

File will get a user's file by id

func (*User) Files

func (u *User) Files(opts ...Option) <-chan *File

Files will return a channel of files.

func (*User) FolderPath

func (u *User) FolderPath(pth string) ([]*Folder, error)

FolderPath will split the path and return a list containing all of the folders in the path.

func (*User) Folders

func (u *User) Folders(opts ...Option) <-chan *Folder

Folders returns a channel of the user's folders.

func (*User) GradedSubmissions

func (u *User) GradedSubmissions() (subs []*Submission, err error)

GradedSubmissions gets the user's graded submissions.

func (*User) ListFiles

func (u *User) ListFiles(opts ...Option) ([]*File, error)

ListFiles will collect all of the users files.

func (*User) ListFolders

func (u *User) ListFolders(opts ...Option) ([]*Folder, error)

ListFolders will return a slice of all the user's folders

func (*User) Profile

func (u *User) Profile() (p *UserProfile, err error)

Profile will make a call to get the user's profile data.

func (*User) Root

func (u *User) Root(opts ...Option) (*Folder, error)

Root will get the root folder for the user's files.

func (*User) SetColor

func (u *User) SetColor(asset, hexcode string) error

SetColor will update the color of the given asset to as specific hex color.

func (*User) Settings

func (u *User) Settings() (settings map[string]interface{}, err error)

Settings will get the user's settings.

func (*User) UploadFile

func (u *User) UploadFile(
	filename string,
	r io.Reader,
	opts ...Option,
) (*File, error)

UploadFile will upload the contents of an io.Reader to a new file in the user's files and return the new file.

type UserColor

type UserColor struct {
	HexCode string `json:"hexcode"`
}

UserColor is just a hex color.

type UserProfile

type UserProfile struct {
	ID             int               `json:"id"`
	LoginID        string            `json:"login_id"`
	Name           string            `json:"name"`
	PrimaryEmail   string            `json:"primary_email"`
	ShortName      string            `json:"short_name"`
	SortableName   string            `json:"sortable_name"`
	TimeZone       string            `json:"time_zone"`
	Bio            string            `json:"bio"`
	Title          string            `json:"title"`
	Calendar       map[string]string `json:"calendar"`
	LTIUserID      string            `json:"lti_user_id"`
	AvatarURL      string            `json:"avatar_url"`
	EffectiveLocal string            `json:"effective_local"`
	IntegrationID  string            `json:"integration_id"`
	Local          string            `json:"local"`
}

UserProfile is a user's profile data.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL