|
|
@@ -8,6 +8,14 @@ enum GoogleClassroomClientError: Error {
|
|
8
|
8
|
|
|
9
|
9
|
/// Minimal Google Classroom REST wrapper for a student's to-do list.
|
|
10
|
10
|
final class GoogleClassroomClient {
|
|
|
11
|
+ struct CreateCourseRequest: Sendable {
|
|
|
12
|
+ var name: String
|
|
|
13
|
+ var section: String?
|
|
|
14
|
+ var room: String?
|
|
|
15
|
+ var descriptionHeading: String?
|
|
|
16
|
+ var description: String?
|
|
|
17
|
+ }
|
|
|
18
|
+
|
|
11
|
19
|
struct Options: Sendable {
|
|
12
|
20
|
var maxCourses: Int
|
|
13
|
21
|
var maxCourseWorkPerCourse: Int
|
|
|
@@ -205,6 +213,94 @@ final class GoogleClassroomClient {
|
|
205
|
213
|
)
|
|
206
|
214
|
}
|
|
207
|
215
|
|
|
|
216
|
+ func createCourse(accessToken: String, request: CreateCourseRequest) async throws -> ClassroomCourse {
|
|
|
217
|
+ let trimmedName = request.name.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
218
|
+ guard trimmedName.isEmpty == false else {
|
|
|
219
|
+ throw GoogleClassroomClientError.decodeFailed("Course name is required.")
|
|
|
220
|
+ }
|
|
|
221
|
+
|
|
|
222
|
+ var payload = CreateCoursePayload(
|
|
|
223
|
+ name: trimmedName,
|
|
|
224
|
+ ownerId: "me",
|
|
|
225
|
+ courseState: "PROVISIONED",
|
|
|
226
|
+ section: request.section?.nonEmptyTrimmed,
|
|
|
227
|
+ room: request.room?.nonEmptyTrimmed,
|
|
|
228
|
+ descriptionHeading: request.descriptionHeading?.nonEmptyTrimmed,
|
|
|
229
|
+ description: request.description?.nonEmptyTrimmed
|
|
|
230
|
+ )
|
|
|
231
|
+ if payload.descriptionHeading == nil, let section = payload.section {
|
|
|
232
|
+ payload.descriptionHeading = section
|
|
|
233
|
+ }
|
|
|
234
|
+
|
|
|
235
|
+ var requestURL = URLRequest(url: URL(string: "https://classroom.googleapis.com/v1/courses")!)
|
|
|
236
|
+ requestURL.httpMethod = "POST"
|
|
|
237
|
+ requestURL.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
|
|
|
238
|
+ requestURL.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
|
239
|
+ requestURL.httpBody = try JSONEncoder().encode(payload)
|
|
|
240
|
+
|
|
|
241
|
+ let (data, response) = try await session.data(for: requestURL)
|
|
|
242
|
+ guard let http = response as? HTTPURLResponse else { throw GoogleClassroomClientError.invalidResponse }
|
|
|
243
|
+ guard (200..<300).contains(http.statusCode) else {
|
|
|
244
|
+ let body = String(data: data, encoding: .utf8) ?? "<no body>"
|
|
|
245
|
+ throw GoogleClassroomClientError.httpStatus(http.statusCode, body)
|
|
|
246
|
+ }
|
|
|
247
|
+
|
|
|
248
|
+ let created: Course
|
|
|
249
|
+ do {
|
|
|
250
|
+ created = try JSONDecoder().decode(Course.self, from: data)
|
|
|
251
|
+ } catch {
|
|
|
252
|
+ let raw = String(data: data, encoding: .utf8) ?? "<unreadable body>"
|
|
|
253
|
+ throw GoogleClassroomClientError.decodeFailed(raw)
|
|
|
254
|
+ }
|
|
|
255
|
+
|
|
|
256
|
+ let acceptedOrCreated: Course
|
|
|
257
|
+ do {
|
|
|
258
|
+ acceptedOrCreated = try await acceptOwnTeachingInvitationIfPresent(accessToken: accessToken, courseId: created.id)
|
|
|
259
|
+ } catch let err as GoogleClassroomClientError where err.isInsufficientScope {
|
|
|
260
|
+ throw err
|
|
|
261
|
+ } catch {
|
|
|
262
|
+ acceptedOrCreated = created
|
|
|
263
|
+ }
|
|
|
264
|
+
|
|
|
265
|
+ let finalizedCourse: Course
|
|
|
266
|
+ if (acceptedOrCreated.courseState ?? "PROVISIONED").uppercased() == "ACTIVE" {
|
|
|
267
|
+ finalizedCourse = acceptedOrCreated
|
|
|
268
|
+ } else {
|
|
|
269
|
+ do {
|
|
|
270
|
+ finalizedCourse = try await updateCourseState(
|
|
|
271
|
+ accessToken: accessToken,
|
|
|
272
|
+ courseId: acceptedOrCreated.id,
|
|
|
273
|
+ courseState: "ACTIVE"
|
|
|
274
|
+ )
|
|
|
275
|
+ } catch let err as GoogleClassroomClientError where err.isInsufficientScope {
|
|
|
276
|
+ throw err
|
|
|
277
|
+ } catch {
|
|
|
278
|
+ finalizedCourse = acceptedOrCreated
|
|
|
279
|
+ }
|
|
|
280
|
+ }
|
|
|
281
|
+
|
|
|
282
|
+ let settledCourse = (try? await waitForCourseToSettle(accessToken: accessToken, courseId: finalizedCourse.id)) ?? finalizedCourse
|
|
|
283
|
+
|
|
|
284
|
+ let teachers = (try? await listCourseTeachers(accessToken: accessToken, courseId: settledCourse.id)) ?? []
|
|
|
285
|
+ let teacherNames = teachers.compactMap { teacher -> String? in
|
|
|
286
|
+ let profileName = teacher.profile?.name?.fullName?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
287
|
+ if let profileName, profileName.isEmpty == false { return profileName }
|
|
|
288
|
+ let email = teacher.profile?.emailAddress?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
289
|
+ if let email, email.isEmpty == false { return email }
|
|
|
290
|
+ return nil
|
|
|
291
|
+ }
|
|
|
292
|
+
|
|
|
293
|
+ return ClassroomCourse(
|
|
|
294
|
+ id: settledCourse.id,
|
|
|
295
|
+ name: (settledCourse.name?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false) ? (settledCourse.name ?? "Course") : "Course",
|
|
|
296
|
+ section: settledCourse.section,
|
|
|
297
|
+ room: settledCourse.room,
|
|
|
298
|
+ teacherNames: teacherNames,
|
|
|
299
|
+ enrollmentCode: settledCourse.enrollmentCode,
|
|
|
300
|
+ courseState: settledCourse.courseState ?? "PROVISIONED"
|
|
|
301
|
+ )
|
|
|
302
|
+ }
|
|
|
303
|
+
|
|
208
|
304
|
// MARK: - Courses
|
|
209
|
305
|
|
|
210
|
306
|
private func listActiveCourses(accessToken: String, pageSize: Int) async throws -> [Course] {
|
|
|
@@ -292,6 +388,120 @@ final class GoogleClassroomClient {
|
|
292
|
388
|
return decoded.teachers ?? []
|
|
293
|
389
|
}
|
|
294
|
390
|
|
|
|
391
|
+ private func updateCourseState(accessToken: String, courseId: String, courseState: String) async throws -> Course {
|
|
|
392
|
+ var components = URLComponents(string: "https://classroom.googleapis.com/v1/courses/\(courseId)")!
|
|
|
393
|
+ components.queryItems = [
|
|
|
394
|
+ URLQueryItem(name: "updateMask", value: "courseState")
|
|
|
395
|
+ ]
|
|
|
396
|
+
|
|
|
397
|
+ var request = URLRequest(url: components.url!)
|
|
|
398
|
+ request.httpMethod = "PATCH"
|
|
|
399
|
+ request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
|
|
|
400
|
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
|
401
|
+ request.httpBody = try JSONEncoder().encode(UpdateCourseStatePayload(courseState: courseState))
|
|
|
402
|
+
|
|
|
403
|
+ let (data, response) = try await session.data(for: request)
|
|
|
404
|
+ guard let http = response as? HTTPURLResponse else { throw GoogleClassroomClientError.invalidResponse }
|
|
|
405
|
+ guard (200..<300).contains(http.statusCode) else {
|
|
|
406
|
+ let body = String(data: data, encoding: .utf8) ?? "<no body>"
|
|
|
407
|
+ throw GoogleClassroomClientError.httpStatus(http.statusCode, body)
|
|
|
408
|
+ }
|
|
|
409
|
+
|
|
|
410
|
+ do {
|
|
|
411
|
+ return try JSONDecoder().decode(Course.self, from: data)
|
|
|
412
|
+ } catch {
|
|
|
413
|
+ let raw = String(data: data, encoding: .utf8) ?? "<unreadable body>"
|
|
|
414
|
+ throw GoogleClassroomClientError.decodeFailed(raw)
|
|
|
415
|
+ }
|
|
|
416
|
+ }
|
|
|
417
|
+
|
|
|
418
|
+ private func acceptOwnTeachingInvitationIfPresent(accessToken: String, courseId: String) async throws -> Course {
|
|
|
419
|
+ for attempt in 0..<3 {
|
|
|
420
|
+ if let invitation = try await listOwnTeacherInvitations(accessToken: accessToken, courseId: courseId).first {
|
|
|
421
|
+ try await acceptInvitation(accessToken: accessToken, invitationId: invitation.id)
|
|
|
422
|
+ return try await fetchCourse(accessToken: accessToken, courseId: courseId)
|
|
|
423
|
+ }
|
|
|
424
|
+ if attempt < 2 {
|
|
|
425
|
+ try await Task.sleep(nanoseconds: 400_000_000)
|
|
|
426
|
+ }
|
|
|
427
|
+ }
|
|
|
428
|
+ return try await fetchCourse(accessToken: accessToken, courseId: courseId)
|
|
|
429
|
+ }
|
|
|
430
|
+
|
|
|
431
|
+ private func listOwnTeacherInvitations(accessToken: String, courseId: String) async throws -> [Invitation] {
|
|
|
432
|
+ var components = URLComponents(string: "https://classroom.googleapis.com/v1/invitations")!
|
|
|
433
|
+ components.queryItems = [
|
|
|
434
|
+ URLQueryItem(name: "userId", value: "me"),
|
|
|
435
|
+ URLQueryItem(name: "courseId", value: courseId)
|
|
|
436
|
+ ]
|
|
|
437
|
+
|
|
|
438
|
+ var request = URLRequest(url: components.url!)
|
|
|
439
|
+ request.httpMethod = "GET"
|
|
|
440
|
+ request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
|
|
|
441
|
+
|
|
|
442
|
+ let (data, response) = try await session.data(for: request)
|
|
|
443
|
+ guard let http = response as? HTTPURLResponse else { throw GoogleClassroomClientError.invalidResponse }
|
|
|
444
|
+ guard (200..<300).contains(http.statusCode) else {
|
|
|
445
|
+ let body = String(data: data, encoding: .utf8) ?? "<no body>"
|
|
|
446
|
+ throw GoogleClassroomClientError.httpStatus(http.statusCode, body)
|
|
|
447
|
+ }
|
|
|
448
|
+
|
|
|
449
|
+ let decoded: InvitationsList
|
|
|
450
|
+ do {
|
|
|
451
|
+ decoded = try JSONDecoder().decode(InvitationsList.self, from: data)
|
|
|
452
|
+ } catch {
|
|
|
453
|
+ let raw = String(data: data, encoding: .utf8) ?? "<unreadable body>"
|
|
|
454
|
+ throw GoogleClassroomClientError.decodeFailed(raw)
|
|
|
455
|
+ }
|
|
|
456
|
+
|
|
|
457
|
+ return (decoded.invitations ?? []).filter { ($0.role ?? "").uppercased() == "TEACHER" }
|
|
|
458
|
+ }
|
|
|
459
|
+
|
|
|
460
|
+ private func acceptInvitation(accessToken: String, invitationId: String) async throws {
|
|
|
461
|
+ var request = URLRequest(url: URL(string: "https://classroom.googleapis.com/v1/invitations/\(invitationId):accept")!)
|
|
|
462
|
+ request.httpMethod = "POST"
|
|
|
463
|
+ request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
|
|
|
464
|
+
|
|
|
465
|
+ let (data, response) = try await session.data(for: request)
|
|
|
466
|
+ guard let http = response as? HTTPURLResponse else { throw GoogleClassroomClientError.invalidResponse }
|
|
|
467
|
+ guard (200..<300).contains(http.statusCode) else {
|
|
|
468
|
+ let body = String(data: data, encoding: .utf8) ?? "<no body>"
|
|
|
469
|
+ throw GoogleClassroomClientError.httpStatus(http.statusCode, body)
|
|
|
470
|
+ }
|
|
|
471
|
+ }
|
|
|
472
|
+
|
|
|
473
|
+ private func fetchCourse(accessToken: String, courseId: String) async throws -> Course {
|
|
|
474
|
+ var request = URLRequest(url: URL(string: "https://classroom.googleapis.com/v1/courses/\(courseId)")!)
|
|
|
475
|
+ request.httpMethod = "GET"
|
|
|
476
|
+ request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
|
|
|
477
|
+
|
|
|
478
|
+ let (data, response) = try await session.data(for: request)
|
|
|
479
|
+ guard let http = response as? HTTPURLResponse else { throw GoogleClassroomClientError.invalidResponse }
|
|
|
480
|
+ guard (200..<300).contains(http.statusCode) else {
|
|
|
481
|
+ let body = String(data: data, encoding: .utf8) ?? "<no body>"
|
|
|
482
|
+ throw GoogleClassroomClientError.httpStatus(http.statusCode, body)
|
|
|
483
|
+ }
|
|
|
484
|
+
|
|
|
485
|
+ do {
|
|
|
486
|
+ return try JSONDecoder().decode(Course.self, from: data)
|
|
|
487
|
+ } catch {
|
|
|
488
|
+ let raw = String(data: data, encoding: .utf8) ?? "<unreadable body>"
|
|
|
489
|
+ throw GoogleClassroomClientError.decodeFailed(raw)
|
|
|
490
|
+ }
|
|
|
491
|
+ }
|
|
|
492
|
+
|
|
|
493
|
+ private func waitForCourseToSettle(accessToken: String, courseId: String) async throws -> Course {
|
|
|
494
|
+ var latest = try await fetchCourse(accessToken: accessToken, courseId: courseId)
|
|
|
495
|
+ if (latest.courseState ?? "").uppercased() == "ACTIVE" { return latest }
|
|
|
496
|
+ for attempt in 0..<4 {
|
|
|
497
|
+ let delayNs: UInt64 = (attempt < 2) ? 350_000_000 : 700_000_000
|
|
|
498
|
+ try await Task.sleep(nanoseconds: delayNs)
|
|
|
499
|
+ latest = try await fetchCourse(accessToken: accessToken, courseId: courseId)
|
|
|
500
|
+ if (latest.courseState ?? "").uppercased() == "ACTIVE" { return latest }
|
|
|
501
|
+ }
|
|
|
502
|
+ return latest
|
|
|
503
|
+ }
|
|
|
504
|
+
|
|
295
|
505
|
private func listCourseAnnouncements(accessToken: String, courseId: String, pageSize: Int) async throws -> [CourseAnnouncement] {
|
|
296
|
506
|
var components = URLComponents(string: "https://classroom.googleapis.com/v1/courses/\(courseId)/announcements")!
|
|
297
|
507
|
components.queryItems = [
|
|
|
@@ -419,6 +629,13 @@ private extension GoogleClassroomClientError {
|
|
419
|
629
|
let lowercasedBody = body.lowercased()
|
|
420
|
630
|
return lowercasedBody.contains("permission_denied") || lowercasedBody.contains("does not have permission")
|
|
421
|
631
|
}
|
|
|
632
|
+
|
|
|
633
|
+ var isInsufficientScope: Bool {
|
|
|
634
|
+ guard case let .httpStatus(status, body) = self, status == 403 else { return false }
|
|
|
635
|
+ let lowercasedBody = body.lowercased()
|
|
|
636
|
+ return lowercasedBody.contains("access_token_scope_insufficient")
|
|
|
637
|
+ || lowercasedBody.contains("insufficient authentication scopes")
|
|
|
638
|
+ }
|
|
422
|
639
|
}
|
|
423
|
640
|
|
|
424
|
641
|
extension GoogleClassroomClientError: LocalizedError {
|
|
|
@@ -450,6 +667,32 @@ private struct Course: Decodable {
|
|
450
|
667
|
let courseState: String?
|
|
451
|
668
|
}
|
|
452
|
669
|
|
|
|
670
|
+private struct CreateCoursePayload: Encodable {
|
|
|
671
|
+ var name: String
|
|
|
672
|
+ var ownerId: String
|
|
|
673
|
+ var courseState: String
|
|
|
674
|
+ var section: String?
|
|
|
675
|
+ var room: String?
|
|
|
676
|
+ var descriptionHeading: String?
|
|
|
677
|
+ var description: String?
|
|
|
678
|
+}
|
|
|
679
|
+
|
|
|
680
|
+private struct UpdateCourseStatePayload: Encodable {
|
|
|
681
|
+ let courseState: String
|
|
|
682
|
+}
|
|
|
683
|
+
|
|
|
684
|
+private struct InvitationsList: Decodable {
|
|
|
685
|
+ let invitations: [Invitation]?
|
|
|
686
|
+ let nextPageToken: String?
|
|
|
687
|
+}
|
|
|
688
|
+
|
|
|
689
|
+private struct Invitation: Decodable {
|
|
|
690
|
+ let id: String
|
|
|
691
|
+ let courseId: String?
|
|
|
692
|
+ let role: String?
|
|
|
693
|
+ let userId: String?
|
|
|
694
|
+}
|
|
|
695
|
+
|
|
453
|
696
|
private struct CourseWorkList: Decodable {
|
|
454
|
697
|
let courseWork: [CourseWork]?
|
|
455
|
698
|
let nextPageToken: String?
|
|
|
@@ -572,6 +815,11 @@ private extension String {
|
|
572
|
815
|
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
|
|
573
|
816
|
return trimmed.isEmpty ? fallback : trimmed
|
|
574
|
817
|
}
|
|
|
818
|
+
|
|
|
819
|
+ var nonEmptyTrimmed: String? {
|
|
|
820
|
+ let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
821
|
+ return trimmed.isEmpty ? nil : trimmed
|
|
|
822
|
+ }
|
|
575
|
823
|
}
|
|
576
|
824
|
|
|
577
|
825
|
private extension Date {
|