Skip to content

Instantly share code, notes, and snippets.

@daranzolin
Last active April 21, 2018 23:55
Show Gist options
  • Save daranzolin/7ddcedfd3176401f01cdd4f0261b598f to your computer and use it in GitHub Desktop.
Save daranzolin/7ddcedfd3176401f01cdd4f0261b598f to your computer and use it in GitHub Desktop.
canvas_url <- function() paste0(Sys.getenv("CANVAS_DOMAIN"), "/api/v1/")
sc <- function(x) {
Filter(Negate(is.null), x)
}
canvas_query <- function(urlx, args, type = "GET") {
fun <- getFromNamespace(type, "httr")
args <- sc(args)
resp <- fun(urlx,
httr::user_agent("rcanvas - https://github.com/daranzolin/rcanvas"),
httr::add_headers(Authorization = paste("Bearer", check_token())),
query = args)
httr::stop_for_status(resp)
return(resp)
}
upload_canvas_file <- function(course_id, file_name, parent_folder_id = NULL, parent_folder_path = "/", on_duplicate = "overwrite") {
if (!is.null(parent_folder_id) && !is.null(parent_folder_path)) stop("Do not specify both parent folder id and parent folder path.")
file_size <- file.info(file_name)$size
url <- paste0(canvas_url(),
paste("courses", course_id, "files", sep = "/"))
args <- sc(list(name = file_name,
size = file_size,
parent_folder_id = parent_folder_id,
parent_folder_path = parent_folder_path,
on_duplicate = on_duplicate))
upload_resp <- canvas_query(url, args, "POST")
upload_content <- httr::content(upload_resp)
upload_url <- upload_content$upload_url
upload_params <- upload_content$upload_params
key_param <- upload_params["key"]
names(key_param) <- "key"
file_param <- file_name
names(file_param) <- "file"
upload_params[["key"]] <- NULL
upload_params <- c(key_param, upload_params, file_param)
httr::POST(url = upload_url,
body = upload_params)
}
upload_canvas_file(course_id = "1185256", file_name = "six.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment