Last active
August 16, 2018 20:40
-
-
Save ianfabs/972b744af803a34f03f73446891b2a7c to your computer and use it in GitHub Desktop.
NodeJS code to copy canvas courses and show the progress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
*Script created by Ian Fabricatore | |
*Please use `node progress-cli.js "<APITOKEN>"` | |
with the quotes | |
*/ | |
const canvas = require('canvas-api-wrapper'); | |
const fs = require('fs'); | |
//Set subdomain | |
canvas.subdomain = "neit"; | |
//APIKey | |
canvas.apiToken = process.argv.slice(2); | |
//const file = "/path/to/file"; | |
const file = "./uploads/test.csv"; | |
function sleep(ms) { | |
return new Promise(resolve => setTimeout(resolve, ms)); | |
} | |
fs.exists(file, (exists) => { | |
if (exists) { | |
//read file | |
fs.readFile(file, 'utf8', (err, contents) => { | |
if (err) throw err; | |
//Split up into an array of individual lines | |
let lines = contents.split("\r\n"); | |
//last one is always blank, so remove it | |
lines.pop(); | |
//loop though each line | |
lines.forEach((els) => { | |
//split line by comma | |
let line = els.split(","); | |
/* | |
*@param line[0] is source course | |
*@param line[1] is target course | |
*/ | |
let source = line[0]; | |
let target = line[1]; | |
let sid, tid; | |
//here we get the ids from canvas based on the course code | |
canvas.get(`/api/v1/courses`, {}, async (err, b) => { | |
//console.log(b); | |
for (i in b) { | |
//If the courscode matches the source | |
if (b[i].course_code == source) { | |
sid = b[i].id; | |
} | |
//If it matches the target | |
if (b[i].course_code == target) { | |
tid = b[i].id; | |
} | |
} | |
//start a course migration | |
let r = await canvas.post(`/api/v1/courses/${tid}/content_migrations`, { | |
migration_type: 'course_copy_importer', | |
settings: { source_course_id: sid }, | |
date_shift_options: { remove_dates: true } | |
}); | |
//show the object | |
console.log(r); | |
//store progress url | |
let progress_url = r.progress_url; | |
//Show progress url | |
console.log(`Progress URL: ${progress_url}`); | |
//set starting progress | |
let progress = 0; | |
while (progress != 100) { | |
//Get current progress | |
let progress_check = await canvas(progress_url); | |
//Display it | |
console.log(`Migration Status: ${progress_check.workflow_state} | ${progress_check.completion}%`) | |
//Update progress | |
progress = Number(progress_check.completion); | |
//Sleep for 3 seconds | |
await sleep(3000); | |
//If complete, break | |
if (progress_check.completion == 100) { | |
console.log("Migration Complete"); | |
break; | |
} | |
} | |
}); | |
}); | |
}); | |
} else throw Error("File not found") | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment