-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclassroom-exporter.gs
More file actions
302 lines (259 loc) · 11.4 KB
/
Copy pathclassroom-exporter.gs
File metadata and controls
302 lines (259 loc) · 11.4 KB
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
const EXPORT_FOLDER_ID = 'FOLDERID'; <-- CHANGE THIS
const COURSE_ID = 'COURSEID'; <-- CHANGE THIS
function exportClassroomData() {
const exportRoot = DriveApp.getFolderById(EXPORT_FOLDER_ID);
const course = Classroom.Courses.get(COURSE_ID);
const courseFolderName = course.name || `course_${COURSE_ID}`;
let courseFolder;
const folders = exportRoot.getFoldersByName(courseFolderName);
if (folders.hasNext()) {
courseFolder = folders.next();
} else {
courseFolder = exportRoot.createFolder(courseFolderName);
}
const usersMap = exportUsersMap(courseFolder);
exportTopics(courseFolder);
exportMaterials(courseFolder, usersMap);
exportCoursework(courseFolder, usersMap);
exportAnnouncements(courseFolder, usersMap);
exportSubmissions(courseFolder, usersMap);
Logger.log("✅ Export completed in folder: " + courseFolderName);
}
// ---------------- USERS MAP ----------------
function exportUsersMap(folder) {
const students = Classroom.Courses.Students.list(COURSE_ID).students || [];
const teachers = Classroom.Courses.Teachers.list(COURSE_ID).teachers || [];
const usersMap = {};
students.forEach(s => usersMap[s.userId] = s.profile.name.fullName);
teachers.forEach(t => usersMap[t.userId] = t.profile.name.fullName);
folder.createFile('users.json', JSON.stringify(usersMap, null, 2), MimeType.PLAIN_TEXT);
return usersMap;
}
// ---------------- TOPICS ----------------
function exportTopics(folder) {
const topics = Classroom.Courses.Topics.list(COURSE_ID).topic || [];
folder.createFile('topics.json', JSON.stringify(topics, null, 2), MimeType.PLAIN_TEXT);
}
// ---------------- MATERIALS ----------------
function exportMaterials(folder, usersMap) {
const materialsFolder = folder.createFolder('materials_files');
const mats = Classroom.Courses.CourseWorkMaterials.list(COURSE_ID).courseWorkMaterial || [];
const exported = mats.map(m => ({
title: m.title,
description: m.description,
authorUserId: m.creatorUserId,
author: usersMap[m.creatorUserId] || '[unknown author]',
topicId: m.topicId,
creationTime: m.creationTime || null,
updateTime: m.updateTime || null,
materials: exportAttachments(m.materials, materialsFolder)
}));
folder.createFile('materials.json', JSON.stringify(exported, null, 2), MimeType.PLAIN_TEXT);
}
// ---------------- COURSEWORK ----------------
function exportCoursework(folder, usersMap) {
const courseworkFolder = folder.createFolder('coursework_files');
const works = Classroom.Courses.CourseWork.list(COURSE_ID).courseWork || [];
const exported = works.map(cw => ({
id: cw.id,
title: cw.title,
description: cw.description,
creatorUserId: cw.creatorUserId,
creatorName: usersMap[cw.creatorUserId] || '[unknown author]',
topicId: cw.topicId,
workType: cw.workType,
assigneeMode: cw.assigneeMode,
individualStudentsOptions: cw.individualStudentsOptions,
creationTime: cw.creationTime || null,
updateTime: cw.updateTime || null,
dueDate: cw.dueDate || null,
dueTime: cw.dueTime || null,
maxPoints: cw.maxPoints || null,
materials: exportAttachments(cw.materials, courseworkFolder)
}));
folder.createFile('coursework.json', JSON.stringify(exported, null, 2), MimeType.PLAIN_TEXT);
}
// ---------------- ANNOUNCEMENTS ----------------
function exportAnnouncements(folder, usersMap) {
const announcementsFolder = folder.createFolder('announcements_files');
const anns = Classroom.Courses.Announcements.list(COURSE_ID).announcements || [];
const exported = anns.map(a => ({
id: a.id,
date: a.updateTime || a.creationTime,
text: a.text,
authorUserId: a.creatorUserId,
author: usersMap[a.creatorUserId] || '[unknown author]',
materials: exportAttachments(a.materials, announcementsFolder),
comments: exportAnnouncementComments(a.id, usersMap)
}));
folder.createFile('announcements.json', JSON.stringify(exported, null, 2), MimeType.PLAIN_TEXT);
}
function exportAnnouncementComments(announcementId, usersMap) {
try {
const comments = Classroom.Courses.Announcements.Comments.list(COURSE_ID, announcementId).comments || [];
return comments.map(c => ({
date: c.updateTime || c.creationTime,
authorId: c.creatorUserId || null,
author: usersMap[c.creatorUserId] || '[unknown author]',
text: c.text
}));
} catch (e) {
Logger.log(`⚠️ Unable to export comments for announcement ${announcementId}: ${e.message}`);
return [];
}
}
// ---------------- SUBMISSIONS ----------------
function exportSubmissions(folder, usersMap) {
const submissionsFolder = folder.createFolder('submissions_files');
const courseworkList = Classroom.Courses.CourseWork.list(COURSE_ID).courseWork || [];
const result = {};
courseworkList.forEach(cw => {
try {
const subs = Classroom.Courses.CourseWork.StudentSubmissions.list(COURSE_ID, cw.id).studentSubmissions || [];
result[cw.id] = {
courseWorkId: cw.id,
title: cw.title,
maxPoints: cw.maxPoints || null,
submissions: subs.map(sub => {
const entry = {
id: sub.id,
userId: sub.userId,
userName: usersMap[sub.userId] || '[unknown student]',
state: sub.state,
assignedGrade: sub.assignedGrade || null,
draftGrade: sub.draftGrade || null,
creationTime: sub.creationTime || null,
updateTime: sub.updateTime || null,
materials: [],
privateComments: exportPrivateComments(cw.id, sub.id, usersMap)
};
try {
if (sub.assignmentSubmission && sub.assignmentSubmission.attachments) {
const subFolder = submissionsFolder.createFolder(sub.id);
entry.materials = sub.assignmentSubmission.attachments.map(mat => {
try {
// ---------------- DRIVE FILE ----------------
if (mat.driveFile) {
const fileId = mat.driveFile.driveFile?.id || mat.driveFile.id;
if (fileId) {
const file = DriveApp.getFileById(fileId);
const title = file.getName();
const mimeType = file.getMimeType();
const googleTypes = {
'application/vnd.google-apps.document': 'docx',
'application/vnd.google-apps.spreadsheet': 'xlsx',
'application/vnd.google-apps.presentation': 'pptx'
};
let saved;
if (googleTypes[mimeType]) {
saved = file.makeCopy(title + '.' + googleTypes[mimeType], subFolder);
return { name: saved.getName(), type: googleTypes[mimeType] };
} else {
saved = file.makeCopy(title, subFolder);
return { name: saved.getName(), type: mimeType };
}
}
// ---------------- LINK ----------------
} else if (mat.link?.url) {
return { type: 'link', url: mat.link.url, title: mat.link.title || '' };
// ---------------- YOUTUBE ----------------
} else if (mat.youtubeVideo?.id) {
return { type: 'youtube', url: `https://youtu.be/${mat.youtubeVideo.id}`, title: mat.youtubeVideo.title || '' };
// ---------------- FORM ----------------
} else if (mat.form?.formUrl) {
return { type: 'form', url: mat.form.formUrl, title: mat.form.title || '' };
} else {
return null;
}
} catch (e) {
Logger.log(`⚠️ Submission attachment not exported (${sub.id}): ${e.message}`);
return null;
}
}).filter(Boolean);
}
} catch (e) {
Logger.log(`⚠️ Unable to export submission ${sub.id}: ${e.message}`);
}
return entry;
})
};
} catch (e) {
Logger.log(`⚠️ Unable to export submissions for coursework ${cw.id}: ${e.message}`);
}
});
folder.createFile('submissions.json', JSON.stringify(result, null, 2), MimeType.PLAIN_TEXT);
}
function exportPrivateComments(courseWorkId, submissionId, usersMap) {
try {
const comments = Classroom.Courses.CourseWork.StudentSubmissions.Comments.list(
COURSE_ID, courseWorkId, submissionId
).comments || [];
return comments.map(c => ({
date: c.updateTime || c.creationTime,
author: usersMap[c.creatorUserId] || '[unknown author]',
text: c.text
}));
} catch (e) {
Logger.log(`⚠️ Private comments not accessible for submission ${submissionId}`);
return [];
}
}
function exportGoogleFileAs(fileId, mimeType, name, targetFolder) {
const url = `https://www.googleapis.com/drive/v3/files/${fileId}/export?mimeType=${encodeURIComponent(mimeType)}`;
const token = ScriptApp.getOAuthToken();
const response = UrlFetchApp.fetch(url, {
headers: { Authorization: `Bearer ${token}` },
muteHttpExceptions: true
});
if (response.getResponseCode() !== 200) {
throw new Error(`Export failed: ${response.getContentText()}`);
}
const blob = response.getBlob().setName(name);
return targetFolder.createFile(blob);
}
// ---------------- ATTACHMENTS EXPORT ----------------
function exportAttachments(materials, targetFolder) {
if (!materials) return [];
return materials.map(mat => {
try {
if (mat.driveFile?.driveFile?.id) {
const fileId = mat.driveFile.driveFile.id;
const fileMeta = Drive.Files.get(fileId);
if (fileMeta.mimeType === 'application/vnd.google-apps.document') {
const saved = exportGoogleFileAs(fileId,
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
fileMeta.title + ".docx",
targetFolder
);
return { name: saved.getName(), type: 'docx' };
} else if (fileMeta.mimeType === 'application/vnd.google-apps.spreadsheet') {
const saved = exportGoogleFileAs(fileId,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
fileMeta.title + ".xlsx",
targetFolder
);
return { name: saved.getName(), type: 'xlsx' };
} else if (fileMeta.mimeType === 'application/vnd.google-apps.presentation') {
const saved = exportGoogleFileAs(fileId,
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
fileMeta.title + ".pptx",
targetFolder
);
return { name: saved.getName(), type: 'pptx' };
} else {
const saved = DriveApp.getFileById(fileId).makeCopy(fileMeta.title, targetFolder);
return { name: saved.getName(), type: fileMeta.mimeType };
}
} else if (mat.link?.url) {
return { type: 'link', url: mat.link.url, title: mat.link.title || '' };
} else if (mat.youtubeVideo?.id) {
return { type: 'youtube', url: `https://youtu.be/${mat.youtubeVideo.id}`, title: mat.youtubeVideo.title || '' };
} else if (mat.form?.formUrl) {
return { type: 'form', url: mat.form.formUrl, title: mat.form.title || '' };
}
} catch (e) {
Logger.log(`⚠️ Attachment not exported: ${e.message}`);
}
return null;
}).filter(Boolean);
}