-
Notifications
You must be signed in to change notification settings - Fork 1
/
canvas_backup
executable file
·348 lines (288 loc) · 10.8 KB
/
canvas_backup
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#!/usr/bin/python3
from lxml import html
import argparse
import http.cookiejar
import json
import os
import re
import requests
import string
import time
API_URL = '/api/v1/'
BASE_URL = None
COOKIE_FILE = None
ONE_MB = 2**20
ONE_KB = 2**10
FILE_COUNT = 0
TOTAL_SIZE = 0
def get_valid_filename(s):
s = str(s).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', s)
def get_file_size(size):
"""
Returns the file size in a human readable format. (e.g. 700.79 KB, 19.55 MB)
"""
if size >= ONE_MB:
return '{:.2f} MB'.format(size / ONE_MB)
elif size >= ONE_KB:
return '{:.2f} KB'.format(size / ONE_KB)
return '{} {}'.format(size, 'bytes')
def write_file(url, filename, path, size, depth):
"""
Writes a file to disk.
"""
global TOTAL_SIZE
global FILE_COUNT
TOTAL_SIZE += size
FILE_COUNT += 1
readable_size = ''
if size != 0:
readable_size = get_file_size(size)
print("{0:>9} {1}{2}".format(readable_size, '|-- ' * depth, filename))
file = requests.get(url, cookies=COOKIE_FILE, stream=True)
filename = get_valid_filename(filename)
with open(path + '/' + filename, 'wb') as f:
for block in file.iter_content(1024):
f.write(block)
def download_file(file, path, depth):
"""
Downloads a file given a canvas file object.
"""
if not file or 'url' not in file or not file['url']:
return 0
write_file(file['url'], file['display_name'], path, file['size'], depth)
return 0
def download_page(html_text, path, name, depth):
"""
Scrapes a standard page for all files on it and downloads them.
"""
files = html_text.find_class('instructure_file_link')
if files:
print("{0:9} {1}{2}/".format('', '|-- ' * depth, name))
try:
path = path + '/' + name
os.mkdir(path)
except:
print('Failed to create an output directory.')
return 1
else:
return 0
for f in files:
file_id = re.search('\/courses\/[0-9]*\/files\/([0-9]*)\/', f.get('href')).group(1)
file_api = API_URL + 'files/' + file_id
file_response = json.loads(requests.get(file_api, cookies=COOKIE_FILE).text[9:])
download_file(file_response, path, depth + 1)
return 0
def download_quiz(quiz, path, depth):
if not quiz or 'html_url' not in quiz or not quiz['html_url']:
return 0
name = get_valid_filename(quiz['title'])
request = quiz['html_url']
response = requests.get(request, cookies=COOKIE_FILE)
if not response:
return 0
download_page(html.document_fromstring(response.content), path, name, depth)
return 0
def download_module_body(page, path, depth):
"""
Parses the body text of a module and finds files to download.
"""
if not page or 'body' not in page or not page['body']:
return 0
name = get_valid_filename(page['title'])
download_page(html.document_fromstring(page['body']), path, name, depth)
return 0
def download_module(module, path, depth):
"""
Downloads all the files in a given canvas module object.
"""
if 'items_url' not in module or 'name' not in module:
return 0
api_request = module['items_url'] + '?per_page=200'
name = get_valid_filename(module['name'])
response = json.loads(requests.get(api_request, cookies=COOKIE_FILE).text[9:])
if not response:
return 0
print("{0:9} {1}{2}/".format('', '|-- ' * depth, name))
try:
path = path + '/' + name
os.mkdir(path)
except:
print('Failed to create an output directory.')
return 1
for r in response:
if 'url' in r:
object = json.loads(requests.get(r['url'], cookies=COOKIE_FILE).text[9:])
if 'body' in object:
# Object is a page: scrape the page for files
download_module_body(object, path, depth + 1)
elif 'quiz_type' in object:
# Object is a quiz: scrape the quiz for files
download_quiz(object, path, depth + 1)
else:
# Object is a file: download the file
download_file(object, path, depth + 1)
return 0
def download_modules(course_id, path, depth=1):
"""
Recursively downloads all the modules in a course.
"""
api_request = API_URL + 'courses/' + course_id + '/modules?per_page=200'
response = json.loads(requests.get(api_request, cookies=COOKIE_FILE).text[9:])
if not response:
return 0
print("{0:9} {1}Modules/".format('', '|-- ' * depth))
try:
os.mkdir(path)
except:
print('Failed to create an output directory.')
return 1
for r in response:
download_module(r, path, depth + 1)
return 0
def download_assignment(assignment_url, path, depth):
"""
Downloads all the files on a given assignment.
"""
response = requests.get(assignment_url, cookies=COOKIE_FILE)
if not response:
return 0
response = html.document_fromstring(response.content)
name = get_valid_filename(response.find_class('assignment-title')[0].find_class('title')[0].text)
download_page(response, path, name, depth)
return 0
def download_assignments(course_id, path, depth=1):
"""
Recursively downloads all assignments for a course given a canvas course id.
"""
api_request = API_URL + 'courses/' + course_id + '/students/submissions?per_page=200'
response = json.loads(requests.get(api_request, cookies=COOKIE_FILE).text[9:])
if not response:
return 0
print("{0:9} {1}Assignments/".format('', '|-- ' * depth))
try:
os.mkdir(path)
except:
print('Failed to create an output directory.')
return 1
for r in response:
assignment_url = BASE_URL + '/courses/%s/assignments/%s' % (course_id, r['assignment_id'])
download_assignment(assignment_url, path, depth+1)
return 0
def download_files(api_request, path, depth):
"""
Downloads all files in a folder given a file list canvas api request.
"""
if not api_request:
return 0
response = json.loads(requests.get(api_request, cookies=COOKIE_FILE).text[9:])
for r in response:
download_file(r, path, depth)
return 0
def download_folder(api_response, path, depth=1, root=False):
"""
Recursively downloads a directory tree given a canvas folder object.
"""
if not api_response or 'folders_url' not in api_response:
return 0
if root:
print("{0:9} {1}Files/".format('', '|-- ' * depth))
try:
os.mkdir(path)
except:
print('Failed to create an output directory.')
return 1
else:
print("{0:9} {1}{2}/".format('', '|-- ' * depth, api_response['name']))
path = path + '/' + get_valid_filename(api_response['name'])
try:
os.mkdir(path)
except:
print('Failed to create an output directory.')
return 1
response = json.loads(requests.get(api_response['folders_url'], cookies=COOKIE_FILE).text[9:])
download_files(api_response['files_url'], path, depth + 1)
for r in response:
download_folder(r, path, depth + 1)
return 0
def download_root(name, asset_string, path):
"""
Recursively downloads all content for a course.
"""
print("{0:9} {1}/".format('', name))
path = path + '/' + get_valid_filename(name)
try:
os.mkdir(path)
except:
print('Failed to create an output directory.')
return 1
asset_attr = asset_string.split('_')
api_req = API_URL + asset_attr[0] + 's/' + asset_attr[1] + '/' + 'folders/root?per_page=200'
response = json.loads(requests.get(api_req, cookies=COOKIE_FILE).text[9:])
download_folder(response, path + '/Files', root=True)
if asset_attr[0] == 'course':
download_assignments(asset_attr[1], path + '/Assignments')
download_modules(asset_attr[1], path + '/Modules')
return 0
def download(args):
global COOKIE_FILE
COOKIE_FILE = http.cookiejar.MozillaCookieJar(args.cookies)
try:
COOKIE_FILE.load(ignore_expires=True)
except:
print('Failed to load the cookie file.\nMake sure the name of the file was entered correctly and that the first line of the cookie file is \'# HTTP Cookie File\'.')
return 1
for c in COOKIE_FILE:
c.expires = time.time() + (24 * 3600)
global API_URL
global BASE_URL
BASE_URL = args.url
API_URL = args.url + API_URL
response = requests.get(BASE_URL + '/files', cookies=COOKIE_FILE)
if response.url != BASE_URL + '/files':
print('Failed to access your canvas files.')
return 1
path = args.output
try:
os.mkdir(path)
except FileExistsError:
print('The directory %s already exists.' % path)
return 1
except:
print('Failed to create an output directory.')
return 1
# Scrapes files page for courses, groups, and user's files.
# Messier than making API calls for courses and groups but easier.
folders = json.loads(html.document_fromstring(response.content).get_element_by_id('application').findtext('script').split(';')[1][9:])['FILES_CONTEXTS']
courses = {}
for f in folders:
courses[f['asset_string']] = f['name']
# Scrape courses page for missing courses since
# the API doesn't return 'inactive' courses.
courses_response = requests.get(BASE_URL + '/courses', cookies=COOKIE_FILE)
courses_response = html.document_fromstring(courses_response.content).find_class('course-list-table-row')
for c in courses_response:
a = c.find_class('course-list-course-title-column')[0].find('a')
if a is not None:
asset_string = 'course_' + a.get('href').split('/')[2]
name = a.get('title')
if asset_string not in courses:
courses[asset_string] = name
for asset_string, name in courses.items():
download_root(name, asset_string, path)
print('')
print('%s files downloaded (%s)' % (FILE_COUNT, get_file_size(TOTAL_SIZE)))
return 0
def main(argv=None):
parser = argparse.ArgumentParser(description='Downloads a complete backup of bCourses.')
parser.usage = """
You need to supply a cookie.txt from your bCourses session.
This can be done, for example, by using the cookies.txt extension in Google Chrome.
You can then grab your cookies.txt file from your canvas page (e.g. https://bcourses.berkeley.edu)."""
parser.add_argument('--cookies', type=str, default='cookies.txt', help='Path to the cookiefile.')
parser.add_argument('--output', type=str, default='downloads', help='Path to the output directory.')
parser.add_argument('--url', type=str, default='https://bcourses.berkeley.edu', help='URL to canvas website.')
args = parser.parse_args(argv)
return download(args)
if __name__ == '__main__':
main()